我希望能够像UIImageView这样的UI对象并在其中平铺图像.
我已经能够使用CGContextDrawTiledImage更新主窗口中的背景,但不能更新图像视图.如果我修改MainView类中的drawRect函数,我可以这样做.
我觉得我很亲密,但仍然缺少一些东西.有人能指出我正确的方向吗?
- (void)drawRect:(CGRect)rect { CGImageRef image = CGImageRetain(currentImage.CGImage); CGRect imageRect; imageRect.origin = CGPointMake(160, 240); imageRect.size = CGSizeMake(320.0, 480.0); CGContextRef uiContext = UIGraphicsGetCurrentContext(); CGContextClipToRect(uiContext, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height)); CGContextDrawTiledImage(uiContext, imageRect, image);
}
如果您只想在视图中平铺图像,请将其更改为普通UIView并使用UIColor initWithPatternImage平铺背景:
backgroundView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageWithContentsOfFile:[self bundlePath:@"some_tile_image.png" inDirectory:@"tiles"]]];
假设你有一个CGImageRef
想要平铺的图像tileImage
和一个UIImageView
被调用的图像imageView
.你需要做的是创建一个UIImage
分配给image
属性的imageView
.你可以这样做:
CGSize imageViewSize = imageView.bounds.size; UIGraphicsBeginImageContext(imageViewSize); CGContextRef imageContext = UIGraphicsGetCurrentContext(); CGContextDrawTiledImage(imageContext, (CGRect){ CGPointZero, imageViewSize }, tileImage); UIImage *finishedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); imageView.image = finishedImage;
这将创建所需大小的位图图像上下文,将图像平铺到该上下文中,从上下文中获取UIImage
,然后将其分配给UIImageView
.只要图像视图和图块图像已加载并准备就绪,您就可以将此代码放在任何位置.