我不会为此使用 UIImageView 。一个普通的 UIView 就足够了。
只需将图像放入图层中
UIView *view = ...
view.layer.contents = (id)image.CGImage;
之后,您可以通过向图层添加蒙版来使部分图像透明
CALayer *mask = [[CALayer alloc] init]
mask.contents = maskimage.CGImage;
view.layer.mask = mask;
对于一个项目,我做了一些事情,我有一个画笔.png,你可以用它来用手指显示图像......我的更新蒙版功能是:
- (void)updateMask {
const CGSize size = self.bounds.size;
const size_t bitsPerComponent = 8;
const size_t bytesPerRow = size.width; //1byte per pixel
BOOL freshData = NO;
if(NULL == _maskData || !CGSizeEqualToSize(size, _maskSize)) {
_maskData = calloc(sizeof(char), bytesPerRow * size.height);
_maskSize = size;
freshData = YES;
}
//release the ref to the bitmat context so it doesn't get copied when we manipulate it later
_maskLayer.contents = nil;
//create a context to draw into the mask
CGContextRef context =
CGBitmapContextCreate(_maskData, size.width, size.height,
bitsPerComponent, bytesPerRow,
NULL,
kCGImageAlphaOnly);
if(NULL == context) {
LogDebug(@"Could not create the context");
return;
}
if(freshData) {
//fill with mask with alpha == 0, which means nothing gets revealed
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
}
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);
//Draw all the points in the array into a mask
for (NSValue* pointValue in _pointsToDraw)
{
CGPoint point;
[pointValue getValue:&point];
//LogDebug(@"location: %@", NSStringFromCGPoint(point));
[self drawBrush:[_brush CGImage] at:point inContext:context];
}
[_pointsToDraw removeAllObjects];
//extract an image from it
CGImageRef newMask = CGBitmapContextCreateImage(context);
//release the context
CGContextRelease(context);
//now update the mask layer
_maskLayer.contents = (id)newMask;
//self.layer.contents = (id)newMask;
//and release the mask as it's retained by the layer
CGImageRelease(newMask);
}