平铺背景图片:我可以使用UIImageView轻松完成吗?

Tha*_*nks 60 iphone uiimageview

我有一个平铺的全屏背景图像,即它必须在水平和垂直方向上再现几次以便制作一个大的.就像在丑陋的主页上的浏览器;)

UIImageView是我的朋友吗?

Bil*_*ney 103

如果我正确理解你的问题,你可以使用colorWithPatternImage:on UIColor然后设置背景颜色UIView.

如果您必须使用a UIImageView,则可以执行相同操作,但无论您在图像视图中放置的任何图像都将在平铺图像前绘制.


小智 30

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

view.backgroundColor = [UIColor colorWithPatternImage:aImage];
view.layer.opaque = NO;
Run Code Online (Sandbox Code Playgroud)

  • `view.layer.opaque = NO;`占优势 (2认同)

Ada*_*dam 16

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

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

的UIImage + Tileable.h

#import <UIKit/UIKit.h>

@interface UIImage (Tileable)

-(UIImage*) imageResizingModeTile;

@end
Run Code Online (Sandbox Code Playgroud)

的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
Run Code Online (Sandbox Code Playgroud)


max*_*lov 12

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

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

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

imageView.image = image.resizableImage(withCapInsets: .zero, resizingMode: .tile)
Run Code Online (Sandbox Code Playgroud)

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

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


Dan*_* T. 8

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

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

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

然后,您可以在storyboard/xib文件中设置背景模式: 该图显示了如何在storyboard/xib中设置colorPattern

  • 这是一个很好的解决方案,但请注意它在启动屏幕xib文件中不起作用."错误:启动屏幕可能不使用用户定义的运行时属性." (3认同)