xcode 如何用 UIImage 填充 CGContext?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11522170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fill CGContext with UIImage?
提问by Radek Wilczak
I subclass UIView
, I overwrite -drawRect:
, I draw a figure by CGContext
. And now I want to fill this figure with UIImage
. Any idea how to do it?
我子类UIView
,我覆盖-drawRect:
,我画一个人物CGContext
。现在我想用UIImage
. 知道怎么做吗?
EDIT:
编辑:
My Code from -drawRect:
我的代码来自 -drawRect:
CGContextBeginPath(ctx);
//here I draw my figure
CGContextClosePath(ctx);
CGContextClip(ctx);
//this doesn't work
UIImage * image = [UIImage imageNamed:@"blackbackground.jgp"];
[image drawInRect:rect];
//this neither
CGImageRef cgImage = image.CGImage;
CGContextDrawImage(ctx, rect, cgImage);
回答by holex
the proper way to draw an image to theCGContext
is this:
将图像绘制到 的正确方法CGContext
是:
UIImage *_originalImage = // your image
UIGraphicsBeginImageContext(_originalImage.size);
CGContextRef _context = UIGraphicsGetCurrentContext(); // here you don't need this reference for the context but if you want to use in the future for drawing anything else on the context you could get it for it
[_originalImage drawInRect:CGRectMake(0.f, 0.f, _originalImage.size.width, _originalImage.size.height)];
UIImage *_newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
回答by Gordon Dove
Assuming that you mean that you want to draw the image 'inside' your figure, the easiest way would be to create a cgpath of your figure, make sure the path is closed, and then CGContextClipToPath( context, path)
假设您的意思是要在图形“内部”绘制图像,最简单的方法是创建图形的 cgpath,确保路径已关闭,然后 CGContextClipToPath(context, path)
ADDED
添加
I've just tested your code, and as Peter said, it should work. I would recommend testing your path ( set the stroke colour and the stroke path), and trying the image without the mask to work out where the problem is.
我刚刚测试了你的代码,正如彼得所说,它应该可以工作。我建议测试您的路径(设置笔触颜色和笔触路径),并尝试不带蒙版的图像以找出问题所在。
回答by Peter Pajchl
What you need is to clip the context with the figure's path and then draw your image. Have a look at this answer which explains how to do the first part How do I add a gradient to the text of a UILabel, but not the background?and once you have the context clipped simply get the UIImage and call one of the drawing functions such as drawInRect...
您需要的是使用图形路径剪辑上下文,然后绘制图像。看看这个答案,它解释了如何做第一部分如何向 UILabel 的文本添加渐变,而不是背景?一旦你剪切了上下文,只需获取 UIImage 并调用其中一个绘图函数,例如 drawInRect ...