【问题标题】:How do I make image-based tiled background for UIView so that it doesn't scale?如何为 UIView 制作基于图像的平铺背景,使其不会缩放?
【发布时间】:2015-07-04 21:08:20
【问题描述】:

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

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

我使用下面的代码来实现它:

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

你能解释一下吗 1. 为什么 ios 会缩放我的图像,以及 2. 不缩放怎么画平铺图?

【问题讨论】:

  • 请不要将您的var命名为“uicolor”...

标签: ios swift uiimage


【解决方案1】:

基本上图像比您的UIView 大。当您提供UIColor(patternImage: image) 时,它使用图像的 1 倍大小。 我们通常在笔记本电脑上使用的图像会根据其纵横比缩放到窗口大小。

因此,将您的图像缩放到您的要求,然后将其应用为背景图像。

【讨论】:

  • 问题是我拥有的图像是用户上传的。有没有办法从代码中以某种方式调整它?
  • @AlexSmolov 建议使用UIImageView 并将ContentMode 设置为`UIViewContentModeScaleAspectFit`
  • @AlexSmolov 这个问题及其答案对你有帮助我猜UIImageView aspect fit and center
  • 谢谢,但除此之外,我还需要我的图案来平铺。
  • 缩小图像的大小,然后将其应用为背景图案。 resuce image size
【解决方案2】:

为了扩展 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!)

【讨论】:

  • 谢谢你,大卫!我发现如果您将@3x(如“myfilepath@3x.png”)添加到图像名称中,它将在每个设备上完美运行。
  • 当时我建议使用 2x,但是是的,这几乎是一样的。
【解决方案3】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 2015-07-03
    • 1970-01-01
    相关资源
    最近更新 更多