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

问题描述 投票:59回答:7

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

UIImageView是我的朋友吗?

iphone uiimageview
7个回答
102
投票

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

如果你必须使用UIImageView,你也可以这样做但是你在图像视图中放置的任何图像都会在平铺图像前面绘制。


30
投票

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

view.backgroundColor = [UIColor colorWithPatternImage:aImage];
view.layer.opaque = NO;

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

的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

8
投票

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

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

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

然后,您可以在storyboard / xib文件中设置背景模式:


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文件时没有调用它。


1
投票

WWDC 2018 video session 219 - Image and Graphics Best Practices,Apple工程师明确建议不要使用图案颜色来平铺背景:

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

因此,创建平铺背景的最佳和最简单的方法是这样的:

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

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

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


0
投票

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

extension UIView {
    var colorPattern:String {
        get {
            return ""  // Not useful here.
        }
        set {
            self.backgroundColor = UIColor(patternImage: UIImage(named:newValue)!)
        }
    }
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.