我想拍摄一张图片(画笔)并将其绘制成一个显示的图像。我只想影响该图像的alpha,我需要稍后导出它。
从我所看到的情况来看,大多数方向只是真正进入一些看起来很昂贵的操作,而这些操作并没有成功。即他们建议你绘制一个屏幕外的上下文,创建一个掩码的CGImage,并在每次刷子应用时创建一个CGImageWithMask。
我已经知道这是昂贵的,因为即使只是这样做并且进入上下文对于iPhone来说相当粗糙。
我想做的是获取UIImageView的UIImage,并直接操作它的alpha通道。我也不是逐像素地做这件事,而是用一个较大的(20px半径)刷子,它具有自己的柔软性。
答案 0 :(得分:6)
我不会为此使用UIImageView。正常的UIView就足够了。
只需将图像放入图层
即可UIView *view = ...
view.layer.contents = (id)image.CGImage;
之后,您可以通过向图层添加蒙版来使图像的一部分透明
CALayer *mask = [[CALayer alloc] init]
mask.contents = maskimage.CGImage;
view.layer.mask = mask;
对于一个项目,我做了一些事情,我有一个brush.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);
}