Set Background Image of a view with stretch to fit

2019-07-15 15:06发布

问题:

I'm new with Xamarin. I'm actually trying to set the background image of a view and stretch it.

The image is a 2048x1536 pixels png.

nfloat vpHeight = View.Bounds.Height;
nfloat vpWidth = View.Bounds.Width;
Console.WriteLine(vpWidth);
Console.WriteLine(vpHeight);

The above code will return me 1024x768 (it's a landscape position).

var img = UIImage.FromFile("pages/p1.png");
UIImageView imgView = new UIImageView(img);
imgView.ContentMode = UIViewContentMode.ScaleAspectFit;

var prevPage = new UIView()
{
    Frame = new CoreGraphics.CGRect(0, 0, vpWidth, vpHeight)
};
prevPage.Add(imgView);

this is the code where I set the background, but the result is just the half of the image in x and y just like the image bellow:

So, how to make the image to adjust to the width and height of the view ?

ty !!

回答1:

I would create an UIImageView as a background like so:

var img = UIImage.FromFile("pages/p1.png");
UIImageView imgView = new UIImageView(img);
imgView.ContentMode = UIViewContentMode.ScaleAspectFit;

then add this to whatever view you are using.

ContentMode can be used like so:

Update I would add it to the prevPage like so:

var prevPage = new UIView()
{
    Frame = new CoreGraphics.CGRect(0, 0, vpWidth, vpHeight)
};

var img = UIImage.FromFile("pages/p1.png");
UIImageView imgView = new UIImageView(new CGRect(0,0,vpWidth,vpHeight));
imgView.Image = img;
imgView.ContentMode = UIViewContentMode.ScaleAspectFit; // or ScaleAspectFill

prevPage.Add(imgView);

Also its worth noting that using the View.Bounds to position the view is bit clunky. I would take a look into Autolayout as you will encounter problems on different devices and orientations. These are some good tutorials on Autolayout they might be native code but you are looking for the relationships of the views rather than the code.

Raywenderlich tutorial

Other Tutorial

Any probs with autolayout just ask another question.



回答2:

I would recommend you stay away from FromPatternImage unless you are really using a pattern.

For the lowest memory consumption and best UI performance, this is what I do:

1st) Resize your image using an image context to match the size of the view:

UIGraphics.BeginImageContext(View.Frame.Size);
UIImage.FromBundle("bg.jpg").Draw(View.Bounds);
var bgImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();

2nd) Display the resized image in a UIImageView and send it to the lowest Z-order:

var uiImageView = new UIImageView(View.Frame);
uiImageView.Image = bgImage;
View.AddSubview(uiImageView);
View.SendSubviewToBack(uiImageView);