iOS绘制UIImage

时间:2015-07-01 10:20:33

标签: ios uiimage drawing

我需要绘制图像涂鸦样式,如下所示。我的问题是我需要能够擦除我绘制的线而不擦除UIImage的部分。目前我考虑使用一个图像作为背景图像,另一个图像使用透明背景,用于涂鸦绘图,然后在绘图完成后将两者合并。有没有更好的办法?

- (void)drawRect:(CGRect)rect
{   
    //Get drawing context
    CGContextRef context = UIGraphicsGetCurrentContext();

    //Create drawing layer if required
    if(drawingLayer == nil)
    {
        drawingLayer = CGLayerCreateWithContext(context, bounds.size, NULL);
        CGContextRef layerContext = CGLayerGetContext(drawingLayer);
        CGContextScaleCTM(layerContext, scale, scale);
        self.viewRect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.width);

        NSLog(@"%f %f",self.viewRect.size.width,self.viewRect.size.width);
    }

    //Draw paths from array
    int arrayCount = [pathArray count];
    for(int i = 0; i < arrayCount; i++)
    {
        path = [pathArray objectAtIndex:i];
        UIBezierPath *bezierPath = path.bezierPath;
        CGContextRef layerContext = CGLayerGetContext(drawingLayer);
        CGContextAddPath(layerContext, bezierPath.CGPath);
        CGContextSetLineWidth(layerContext, path.width);
        CGContextSetStrokeColorWithColor(layerContext, path.color.CGColor);
        CGContextSetLineCap(layerContext, kCGLineCapRound);

        if(activeColor == 4)
        {
            CGContextSetBlendMode(layerContext, kCGBlendModeClear);
        }
        else
        {
            CGContextSetBlendMode(layerContext, kCGBlendModeNormal);
        }

        CGContextStrokePath(layerContext);
    }

    if (loadedImage == NO)
    {
        loadedImage = YES;
    CGContextRef layerContext = CGLayerGetContext(drawingLayer);
    CGContextSaveGState(layerContext);
    UIGraphicsBeginImageContext (self.viewRect.size);
    CGContextTranslateCTM(layerContext, 0, self.viewRect.size.height);
    CGContextScaleCTM(layerContext, 1.0, -1.0);
    CGContextDrawImage(layerContext, self.viewRect, self.image.CGImage);
    UIGraphicsEndImageContext();
    CGContextRestoreGState(layerContext);
    }

    [pathArray removeAllObjects];

    CGContextDrawLayerInRect(context, self.viewRect, drawingLayer);
}

enter image description here

0 个答案:

没有答案