3

在我的应用中有一个 imageViewA (frame{0,0,320,200}),我想以 imageViewA 的中心,radius=50 剪辑一个圆,然后绘制到另一个 imageViewB (frame{0,0,100,100});原图效果如下:

在此处输入图像描述

并使用以下代码进行剪辑:

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];
}

剪辑图像效果如下:

在此处输入图像描述

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

4

4 回答 4

6
imageViewB.layer.cornerRadius = 50.0;
imageViewB.layer.masksToBounds = YES;
于 2014-01-07T23:41:59.867 回答
2

JPEG doesn't support transparency. Use UIImagePNGRepresentation instead of UIImageJPEGRepresentation, and you will have the result you want.

NSData *imageData = UIImagePNGRepresentation(newImage);
if([imageData writeToFile:headerPath atomically:YES]){
    imageViewB.image = [UIImage imageWithContentsOfFile:headerPath];
}
于 2013-11-07T12:39:16.200 回答
0

在绘制图像之前:

CGContextSetBlendMode(ctx, kCGBlendModeClear);
CGContextFillRect(ctx, self.bounds);
CGContextSetBlendMode(ctx, kCGBlendModeNormal);
于 2014-05-19T13:54:58.007 回答
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。

于 2013-11-07T10:27:35.180 回答