水平和垂直重复图像

Repeat image horizontally and vertically

我要重复下图:

实现如下背景:

我试了几个代码如下:

bluePatternView.backgroundColor = [UIColor colorWithPatternImage:
    [[UIImage imageNamed:@"blue_pattern.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0]];

和:

bluePatternView.backgroundColor = 
    [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"blue_pattern.png"]];

我也尝试用 CGContextDrawTiledImage 绘制图像,但没有成功。

怎么做到的?!

编辑:实施 luk2302 的结果。请通过投票给予他认可

bluePatternView.backgroundColor = 
  [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue_pattern.png"]];

结果:

这是使用 stretchableImageWithLeftCapWidth 的 Bellow 方法,就像这样:-

UIImage *backgroundImage = [[UIImage imageNamed:@"SheetBackground.png"] stretchableImageWithLeftCapWidth:0.5 topCapHeight:0];

按照您的需要示例:-

UIImage *backgroundImage = [[UIImage imageNamed:@"q4Ses.png"] stretchableImageWithLeftCapWidth:0.5 topCapHeight:0];

  [_scro setBackgroundColor:[UIColor colorWithPatternImage:backgroundImage]];

正如我的评论所说:使用

bluePatternView.backgroundColor = 
  [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue_pattern.png"]];

您不想拉伸图像。让 UIKit 负责重复。

假设您的 bluePatternView 是您要为其设置图案作为背景的实际大视图。如果该代码仍然无法正常工作,可能是您设置了错误视图的背景 属性。

注意:复制带有@2x 和@3x 扩展名的SAME 图像将导致更高分辨率设备的正确行为。

我在 images.xcassets,

中找到了解决方案

第 1 步:- 将您的图像放入 images.xcassets

第二步:-点击图片,然后点击右下角的“Show Slicing”

第 3 步:- 点击开始切片

第 4 步:- 点击 "Slice Horizontally and Vertically" 按钮

第 5 步:- 在这里您将看到 3 条水平和 3 条垂直切片线。

  • 将最左边的垂直线放在图像的左侧,将最右边的两条垂直线放在图像的右侧。
  • 将最上面的线放在图像的顶部,将最下面的两条线放在图像的底部。
  • 因此最终结果将如下所示。

第 6 步:- 使用此图像。

现在将重复图像。

注意:- 如果对 2x 图像进行切片,它只会重复 2x 图像,对于 3x 图像,您需要进行相同的切片。

Example by Apple

bluePatternView.backgroundColor = UIColor(patternImage: UIImage(named: "blue_pattern")!)

您需要将图像保存在资产中,然后将这些行放入 viewdidload

bluePatternView.backgroundColor = UIColor.init(patternImage: #imageLiteral(resourceName: "f8"))

这是针对 Swift 4.1.