65

我有一个平铺的全屏背景图像,即它必须水平和垂直复制几次才能制作一个大的。就像在丑陋主页上的浏览器中一样;)

UIImageView 是我的朋友吗?

4

7 回答 7

105

如果我正确理解您的问题,您可以使用colorWithPatternImage:onUIColor然后将背景颜色设置为UIView.

如果您必须使用 aUIImageView您可以执行相同的操作,但是您放置在图像视图中的任何图像都将绘制在平铺图像的前面。

于 2009-07-14T13:04:03.810 回答
30

要使 alpha 与图案图像一起使用,请确保您具有以下设置:

view.backgroundColor = [UIColor colorWithPatternImage:aImage];
view.layer.opaque = NO;
于 2011-01-03T22:30:06.967 回答
17

多年来我一直使用 Bill Dudney 的方法,但 iOS 6 有一个更好的解决方案。而且......今天我找到了一种方法可以在旧版本的 iOS 上进行这项工作。

  1. 创建新类“UIImage+Tileable”(复制/粘贴下面的源代码)
  2. 将其导入您想要带有可平铺图像的 UIImageView 的任何类中。这是一个类别,因此它使用标准的 Apple 调用将所有 UIImage 都“升级”为可平铺的
  3. 当您想要图像的“平铺”版本时,请调用:“image = [image imageResizingModeTile]”

UIImage+Tileable.h

#import <UIKit/UIKit.h>

@interface UIImage (Tileable)

-(UIImage*) imageResizingModeTile;

@end

UIImage+Tileable.m

#import "UIImage+Tileable.h"

@implementation UIImage (Tileable)

-(UIImage*) imageResizingModeTile
{
    float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];

    if( iOSVersion >= 6.0f )
    {
        return [self resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeTile];
    }
    else
    {
        return [self resizableImageWithCapInsets:UIEdgeInsetsZero];
    }
}
@end
于 2013-05-10T10:38:45.840 回答
14

WWDC 2018 视频会话 219 - Image and Graphics Best Practices中,Apple 工程师明确建议不要将图案颜色用于平铺背景:

我建议不要在 UIView 上使用带有背景颜色属性的图案颜色。相反,创建一个 UIImageView。将您的图像分配给该图像视图。并使用 UIImageView 上的功能来适当地设置您的平铺参数。

所以创建平铺背景的最好和最简单的方法是这样的:

imageView.image = image.resizableImage(withCapInsets: .zero, resizingMode: .tile)

或者更简单,如果您使用资产目录 - 选择您的图案图像资产,然后在属性检查器中启用切片(水平/垂直或两者),将插图设置为零,将宽度/高度设置为图像的尺寸:

然后只需将此图像分配给您的图像视图(Interface Builder 也可以),只是不要忘记将 UIImageView 设置contentMode.scaleToFill.

于 2019-04-01T16:03:44.730 回答
8

我使用@Rivera 解决方案的变体:

将以下内容放在 UIView 扩展中:

- (void)setColorPattern:(NSString *)imageName
{
    [self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:imageName]]];
}

然后可以在storyboard/xib文件中设置背景图案: 显示如何在情节提要/xib 中设置 colorPattern 的图像

于 2015-04-29T19:58:42.507 回答
4

因为我真的很喜欢 Interface Builder,所以我创建了这个UIImageView子类来应用平铺背景:

@interface PETiledImageView : UIImageView

@end

@implementation PETiledImageView

- (void)awakeFromNib
{
    [super awakeFromNib];

    UIImage * imageToTile = self.image;
    self.image = nil;
    UIColor * tiledColor = [UIColor colorWithPatternImage:imageToTile];
    self.backgroundColor = tiledColor;
}

@end

我尝试了覆盖setImage:,但似乎 IB 在解码 Nib 文件时没有调用它。

于 2014-06-10T02:28:32.323 回答
0

Daniel T 解决方案的 Swift 版本。您仍然需要在 IB 中设置 keyPath 值。当然,您可以更加小心地打开 Optional UIImage。

extension UIView {
    var colorPattern:String {
        get {
            return ""  // Not useful here.
        }
        set {
            self.backgroundColor = UIColor(patternImage: UIImage(named:newValue)!)
        }
    }
}
于 2016-11-23T21:07:55.877 回答