使用CGContextClip剪切带图像的圆圈

时间:2013-11-07 10:16:16

标签: ios cgcontextref

在我的应用程序中有一个imageViewA(第{0,0,320,200}帧),我想用imageViewA的中心剪切一个圆,半径= 50,并绘制到另一个imageViewB(第{0,0,100,100}帧); 像这样的原始图像效果:

enter image description here

并使用以下代码剪辑:

UIGraphicsBeginImageContext(self.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat height = self.bounds.size.height;
CGContextTranslateCTM(ctx, 0.0, height);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextAddArc(ctx, self.frame.size.width/2, self.frame.size.height/2, 50, 0, 2*M_PI, 0);
CGContextClosePath(ctx);
CGContextSaveGState(ctx);
CGContextClip(ctx);
CGContextDrawImage(ctx, CGRectMake(0,0,self.frame.size.width, self.frame.size.height), image.CGImage);
CGContextRestoreGState(ctx);
CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
NSString *headerPath = [NSString stringWithFormat:@"%@/header.png",HomeDirectory];
NSData *imageData = UIImageJPEGRepresentation(newImage, 1.0);
if([imageData writeToFile:headerPath atomically:YES]){
    imageViewB.image = [UIImage imageWithContentsOfFile:headerPath];
}

像这样剪辑图像效果:

enter image description here

我只需要圆形视图,但剪辑效果显示imageViewB有空白区域。 如何正确剪辑此图片? 谢谢!

4 个答案:

答案 0 :(得分:6)

imageViewB.layer.cornerRadius = 50.0;
imageViewB.layer.masksToBounds = YES;

答案 1 :(得分:1)

JPEG不支持透明度。使用UIImagePNGRepresentation代替UIImageJPEGRepresentation,您将获得所需的结果。

NSData *imageData = UIImagePNGRepresentation(newImage);
if([imageData writeToFile:headerPath atomically:YES]){
    imageViewB.image = [UIImage imageWithContentsOfFile:headerPath];
}

答案 2 :(得分:0)

为此目的使用遮蔽 此代码将帮助您屏蔽图像

+ (UIImage *)maskImage:(UIImage *)image withMask:(UIImage *)maskImage
{
    CGImageRef maskRef = maskImage.CGImage;
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    UIImage *uiMasked = [UIImage imageWithCGImage:masked];
    CFRelease(mask);
    CFRelease(masked);
    return uiMasked;
}

这篇文章可以帮到你 http://www.abdus.me/ios-programming-tips/how-to-mask-image-in-ios-an-image-masking-technique/

屏蔽后,您需要使用该蒙版图像创建一个imageView 然后将其子视图转换为另一个imageView。

答案 3 :(得分:0)

在绘制图像之前:

CGContextSetBlendMode(ctx, kCGBlendModeClear);
CGContextFillRect(ctx, self.bounds);
CGContextSetBlendMode(ctx, kCGBlendModeNormal);