如何使用CGContextDrawTiledImage来平铺图像? [英] How can I use CGContextDrawTiledImage to tile an image?

查看:442
本文介绍了如何使用CGContextDrawTiledImage来平铺图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个像UIImageView这样的UI对象,并且在其内部绘制一个图像。

I want to be able to an UI object like a UIImageView and tile an image inside of it.

我已经能够使用CGContextDrawTiledImage来更新背景主窗口,但不是图像视图。我可以这样做,如果我修改的MainView类中的drawRect函数。

I have been able to use CGContextDrawTiledImage to update the background in the main window, but not an image view. I can do this if I modify the drawRect function inside the MainView class.

我觉得我很接近,但仍然缺少一些东西。有人可以指点我的方向吗?

I feel I'm close, but still missing something. Can someone point me in the right direction?

- (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);

}

推荐答案

假设你有一个 CGImageRef 为你想要的图片调用 tileImage UIImageView 调用 imageView 。你需要做的是创建一个 UIImage 分配给 image 属性 imageView 。你可以这样做:

Let's say you've got a CGImageRef for the image you want to tile called tileImage and a UIImageView called imageView. What you need to do is create a UIImage to assign to the image property of imageView. You can do that like this:

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 。只要图片视图和图片图片已加载并准备就绪,您就可以将此代码放在任何位置。

This will create a bitmap image context of the desired size, tile the image into that context, get a UIImage out of the context, then assign it to the UIImageView. You can really put this code anywhere so long as the image view and tile image are loaded and ready to go.

这篇关于如何使用CGContextDrawTiledImage来平铺图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆