如何在iPhone SDK中将正方形图像蒙上圆角图像? [英] How to mask a square image into an image with round corners in the iPhone SDK?
本文介绍了如何在iPhone SDK中将正方形图像蒙上圆角图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你如何将一个正方形图像掩盖成一个带有圆角的图像?你可以使用CoreGraphics创建一个路径对于这个代码片段的圆形矩形:
static void addRoundedRectToPath(CGContextRef context,CGRect rect,float ovalWidth,float ovalHeight)
{
float fw,fh;
if(ovalWidth == 0 || ovalHeight == 0){
CGContextAddRect(context,rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM(context,CGRectGetMinX(rect),CGRectGetMinY(rect));
CGContextScaleCTM(context,ovalWidth,ovalHeight);
fw = CGRectGetWidth(rect)/ ovalWidth;
fh = CGRectGetHeight(rect)/ ovalHeight;
CGContextMoveToPoint(context,fw,fh / 2);
CGContextAddArcToPoint(context,fw,fh,fw / 2,fh,1);
CGContextAddArcToPoint(context,0,fh,0,fh / 2,1);
CGContextAddArcToPoint(context,0,0,fw / 2,0,1);
CGContextAddArcToPoint(context,fw,0,fw,fh / 2,1);
CGContextClosePath(context);
CGContextRestoreGState(context);
}
然后调用CGContextClip(context);将其剪切到矩形路径。现在,任何完成的绘图(包括绘制图像)都将被裁剪成圆形的矩形形状。
例如,假设image是UIImage,并且这是一个drawRect:方法:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
addRoundedRectToPath(context,self.frame,10,10);
CGContextClip(context);
[image drawInRect:self.frame];
CGContextRestoreGState(context);
How can you mask a square image into an image with round corners?
解决方案
You can use CoreGraphics to create a path for a round rectangle with this code snippet:
static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM (context, ovalWidth, ovalHeight);
fw = CGRectGetWidth (rect) / ovalWidth;
fh = CGRectGetHeight (rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2);
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
CGContextClosePath(context);
CGContextRestoreGState(context);
}
And then call CGContextClip(context); to clip it to the rectangle path. Now any drawing done, including drawing an image, will be clipped to the round rectangle shape.
As an example, assuming "image" is a UIImage, and this is in a drawRect: method:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
addRoundedRectToPath(context, self.frame, 10, 10);
CGContextClip(context);
[image drawInRect:self.frame];
CGContextRestoreGState(context);
这篇关于如何在iPhone SDK中将正方形图像蒙上圆角图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文