我有一个平铺的全屏背景图像,即它必须水平和垂直复制几次才能制作一个大的。就像在丑陋主页上的浏览器中一样;)
UIImageView 是我的朋友吗?
如果我正确理解您的问题,您可以使用colorWithPatternImage:
onUIColor
然后将背景颜色设置为UIView
.
如果您必须使用 aUIImageView
您可以执行相同的操作,但是您放置在图像视图中的任何图像都将绘制在平铺图像的前面。
要使 alpha 与图案图像一起使用,请确保您具有以下设置:
view.backgroundColor = [UIColor colorWithPatternImage:aImage];
view.layer.opaque = NO;
多年来我一直使用 Bill Dudney 的方法,但 iOS 6 有一个更好的解决方案。而且......今天我找到了一种方法可以在旧版本的 iOS 上进行这项工作。
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
在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
.
我使用@Rivera 解决方案的变体:
将以下内容放在 UIView 扩展中:
- (void)setColorPattern:(NSString *)imageName
{
[self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:imageName]]];
}
然后可以在storyboard/xib文件中设置背景图案:
因为我真的很喜欢 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 文件时没有调用它。
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)!)
}
}
}