使用拉伸设置视图的背景图像以适合 Xamarin [英] Set Background Image of a view with stretch to fit in Xamarin

查看:39
本文介绍了使用拉伸设置视图的背景图像以适合 Xamarin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Xamarin 的新手.我实际上是在尝试设置视图的背景图像并对其进行拉伸.

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

图片是 2048x1536 像素的 png.

The image is a 2048x1536 pixels png.

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

上面的代码将返回 1024x768(这是一个横向位置).

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);

这是我设置背景的代码,但结果只是 x 和 y 中图像的一半,就像下面的图像:

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 ?

你好!!

推荐答案

我会像这样创建一个 UIImageView 作为背景:

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 可以这样使用:

ContentMode can be used like so:

更新我会像这样将它添加到 prevPage 中:

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);

另外值得注意的是,使用 View.Bounds 来定位视图有点笨拙.我会研究一下 Autolayout,因为您会在不同的设备和方向上遇到问题.这些是关于自动布局的一些很好的教程,它们可能是本机代码,但您正在寻找视图的关系而不是代码.

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 教程

其他教程

任何关于自动布局的问题都可以问另一个问题.

Any probs with autolayout just ask another question.

这篇关于使用拉伸设置视图的背景图像以适合 Xamarin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆