如何为 UIView 制作基于图像的平铺背景,使其无法缩放?

How do I make image-based tiled background for UIView so that it doesn't scale?

在 iOS 应用程序中,我有 250x85pt UIView。我希望它有基于图像的平铺背景。原始图像为 398x398 像素。我想要平铺我的图像。

当我 运行 应用程序时,我的图像平铺,但由于某种原因它缩放如下:

我是用下面的代码实现的:

var image = UIImage(contentsOfFile: "myfilepath.png")!
var uicolor = UIColor(patternImage: image)
uiview.backgroundColor = uicolor

你能解释一下吗 1. 为什么 ios 缩放我的图像,以及 2. 如何在不缩放的情况下绘制平铺图像?

基本上图像比您的 UIView 大。当你给 UIColor(patternImage: image) 它使用图像的 1x 大小。 我们通常在笔记本电脑上使用的图片会根据纵横比缩放到 window 大小。

因此请根据您的要求缩放图片,然后将其用作背景图片。

为了扩展 Banto 的回答,问题是您的视图是 250x85 点,在视网膜设备上实际上是 500x170 像素。当您的 x1 图像变成图案时,它会在点级别应用。通过将图像上的比例设置为与设备上的比例相匹配,可以很容易地改变这个问题:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 85))

let image = UIImage(named: "myfilepath.png")!
let scaled = UIImage(CGImage: image.CGImage, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)

view.backgroundColor = UIColor(patternImage: scaled!)

试试这个

 self.mainView.layer.contents = (id)[UIImage imageNamed:@"CROPNET.png"].CGImage;