我对CoreGraphics很新(虽然我已经做了一段时间的iphone编程)
问题,我有这个按比例缩放的片段,并将UIImage剪辑为圆圈:
-(UIImage *)counterpartImageForSchedule:(Schedule *)counterpartSchedule inSize:(CGSize)size
{
// This function returns a newImage, based on image, that has been:
// - scaled to fit in (CGRect) rect
// - and cropped within a circle of radius: rectWidth/2
UIImage *image=[UIImage imageNamed:@"fakeuser1.png"];
// when kendy sends hash, check that this image is not on the cache, otherwise download, clip & stylized
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
//Get the width and heights
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGFloat rectWidth = size.width;
CGFloat rectHeight = size.height;
//Calculate the scale factor
CGFloat scaleFactorX = rectWidth/imageWidth;
CGFloat scaleFactorY = rectHeight/imageHeight;
if (scaleFactorX>scaleFactorY) {
scaleFactorY=scaleFactorX;
} else
{
scaleFactorX=scaleFactorY;
}
//Calculate the centre of the circle
CGFloat imageCentreX = rectWidth/2;
CGFloat imageCentreY = rectHeight/2;
// Create and CLIP to a CIRCULAR Path
// (This could be replaced with any closed path if you want a different shaped clip)
CGFloat radius = rectWidth/2;
CGContextBeginPath (context);
CGContextAddArc (context, imageCentreX, imageCentreY, radius, 0, 2*M_PI, 0);
CGContextClosePath (context);
CGContextClip (context);
//Set the SCALE factor for the graphics context
//All future draw calls will be scaled by this factor
CGContextScaleCTM (context, scaleFactorX, scaleFactorY);
// the stroke
// Draw the IMAGE
CGRect myRect = CGRectMake(0, 0, imageWidth, imageHeight);
[image drawInRect:myRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
问题是,我如何描绘我用来剪辑图像的路径(例如,4个像素,黑色或白色)?我需要画一个新的吗?
非常感谢任何帮助!
答案 0 :(得分:1)
路径可以是任何其他对象 - 在本例中是CGPath(CGPathRef)。在使用任何路径之前,将其封装为CGPath(在这种情况下,可能是CGMutablePathRef,或者您可以在使用剪辑路径之前调用CGContextCopyPath)。现在您可以重用该路径。
以下是我的一个应用程序中的示例,其中我构建了一个路径,然后将其描边,然后剪切到相同的路径(c
是图形上下文):
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, CGRectGetMaxX(r) - radius, ins);
CGPathAddArc(path, nil,
radius+ins, radius+ins, radius, -M_PI/2.0, M_PI/2.0, true);
CGPathAddArc(path, nil,
CGRectGetMaxX(r) - radius, radius+ins, radius, M_PI/2.0, -M_PI/2.0, true);
CGPathCloseSubpath(path);
CGContextAddPath(c, path);
CGContextSetLineWidth(c, 2);
CGContextStrokePath(c);
CGContextAddPath(c, path);
CGContextClip(c);
CGPathRelease(path);
另一种可能性是使用UIBezierPath - 一个完整的Objective-C对象,而不是CGContext函数。它封装了一个CGPath,你可以重用那个路径 - 剪辑它,然后抚摸它。或者反过来说。