2013-03-22 248 views
3

我有一个图像可以在水平方向拉伸,但需要垂直平铺(一个在另一个顶部)以填充我的视图。我怎么能这样做?如何垂直平铺UIImage,而只在iOS上水平拉伸?

我知道使用-(UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets方法可以调整图像大小。所以这对于水平方向很好,但是这种方法不能用于垂直方向,它需要平铺,并且不能在垂直方向拉伸工作。

现在我的想法是如何工作的是运行一个循环,用水平拉伸的图像创建UIImageView,并简单地调整frame.origin.y属性,然后将其作为每个循环的子视图添加,直到我超过了视野的高度。然而,这似乎是一个过度复杂的做法,当视图需要调整大小时(例如在iPad上旋转),这实际上并不实际。

在iOS 6.x上有更简单更有效的方法吗?

回答

1

您是否考虑过使用UIColor的方法colorWithPatternImage:来创建一个重复图案,并传递正确的水平宽度的图像?

代码示例:

// On your desired View Controller 

- (void)viewDidLoad 
{ 
     [super viewDidLoad]; 
     UIImage *patternImage = [UIImage imageNamed:@"repeating_pattern"]; 
     self.view.backgroundColor = [UIColor colorWithPatternImage:patternImage]; 

     // ... do your other stuff here... 
} 
+1

是的我有,这种方法的问题是,我会需要一个图像我会支持每个视图宽度。因此,在这种情况下,iPhone为320px,然后iPad为横向和纵向宽度。三听起来可能听起来不多,但我希望我的代码能够适应任何情况。基本上我想要将来证明它。 – gossainapps 2013-03-22 22:20:12

+0

这里有一个权衡。像这样设置backgroundColor会导致[应用程序中出现泄漏](http://stackoverflow.com/questions/9703396/ios-high-memory-usage)。我还不确定是否有更好的选择,所以这更多的是让你知道。 – Maxwell 2014-12-17 16:22:27

0

所以我想通了一个解决方案。这是我觉得有点笨拙,但它的工作原理。

基本上我所做的就是用指定的左右帽来创建我的可拉伸图像。然后我用它初始化一个UIImageView。然后我调整图像视图的框架到所需的宽度。这将适当调整其中包含的图像的大小。

然后最后我用了一段我发现的代码,通过垂直平铺现在包含在图像视图中的调整图像来创建一个新图像。请注意,如何访问原始UIImage而不是使用UIImageView视图的图像属性。

的最后一件事然后是设置新的UIImage作为视图

这里的背景图案颜色的代码:

// create a strechable image 
     UIImage *image = [[UIImage imageNamed:@"[email protected]"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 60, 0, 60)]; 

     // create the image view that will contain it 
     UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
     CGRect frame = imageView.frame; 
     frame.size.width = self.view.bounds.size.width; 
     imageView.frame = frame; 

     // create the tiled image 
     CGSize imageViewSize = imageView.bounds.size; 
     UIGraphicsBeginImageContext(imageViewSize); 
     CGContextRef imageContext = UIGraphicsGetCurrentContext(); 
     CGContextDrawTiledImage(imageContext, (CGRect){ CGPointZero, imageViewSize }, imageView.image.CGImage); 
     UIImage *finishedImage = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 

     self.view.backgroundColor = [UIColor colorWithPatternImage:finishedImage]; 
+0

我很确定'imageView.image.CGImage'应该和'image.CGImage'一样;神奇发生在其他地方。 – 2013-03-22 23:39:19

+0

@gossainapps查看我的回答。=) – fumoboy007 2013-03-23 00:42:28

1
UIImage *image = [UIImage imageNamed:@"test.png"]; 
UIImage *resizableImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, image.size.width/2, 0, image.size.width/2)]; 
+0

未解决,因为它在中间拉伸,而不是垂直重复 – 2014-05-30 11:17:02

2

我用这个横向平铺在图像一个UIImageView:

UIImage *image = [UIImage imageNamed:@"my_image"]; 
UIImage *tiledImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeTile]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:tiledImage]; 

这假定你设置UIImageView的框架为一个更大大小超过您的图片资产。如果高度比图像高,它也会垂直平铺。