3

我想拍摄图像(画笔)并将其绘制到显示的图像中。我只想影响该图像的 alpha,稍后需要将其导出。

据我所见,大多数方向只是真正涉及一些看起来成本高昂但没有成功的操作。即,他们建议您绘制到屏幕外上下文中,创建蒙版的 CGImage,并且几乎每次应用画笔时都创建一个 CGImageWithMask。

我已经知道这很昂贵,因为即使只是这样做并绘制到上下文中对于 iPhone 来说也是相当粗糙的。

我想做的是获取 UIImageView 的 UIImage,并直接操作它的 alpha 通道。我也不是逐个像素地进行,而是使用具有自身柔软度的较大(20px 半径)笔刷。

4

1 回答 1

6

我不会为此使用 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);
}
于 2011-04-27T16:10:19.707 回答