2

我需要来自 Masked CALayer 的 UIImage。这是我使用的功能:

- (UIImage *)imageFromLayer:(CALayer *)layer
{
    UIGraphicsBeginImageContext([layer frame].size);

    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return outputImage;
}

问题是没有维护面具。这是完成的代码:

    CAShapeLayer * layerRight= [CAShapeLayer layer];
    layerRight.path = elasticoRight;
    im2.layer.mask = layerRight;

    CAShapeLayer * layerLeft= [CAShapeLayer layer];
    layerLeft.path = elasticoLeft;
    im3.layer.mask = layerLeft;

    [viewImage.layer addSublayer:im2.layer];
    [viewImage.layer addSublayer:im3.layer];


    UIImage *image_result = [self imageFromLayer:viewImage.layer];

如果我将 viewImage 可视化,结果是正确的,但如果我尝试获取相对于图层的图像,则会丢失蒙版。

4

1 回答 1

1

我已经解决了。现在我获取图像蒙版并使用 CGContextClipToMask。

CGRect rect = CGRectMake(0, 0, 1024, 768);

UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0);

{
   [[UIColor blackColor] setFill];
   UIRectFill(rect);
   [[UIColor whiteColor] setFill];

   UIBezierPath *leftPath = [UIBezierPath bezierPath];

   // Set the starting point of the shape.
   CGPoint p1 = [(NSValue *)[leftPoints objectAtIndex:0] CGPointValue];
   [leftPath moveToPoint:CGPointMake(p1.x, p1.y)];

   for (uint i=1; i<leftPoints.count; i++)
   {
       CGPoint p = [(NSValue *)[leftPoints objectAtIndex:i] CGPointValue];
       [leftPath addLineToPoint:CGPointMake(p.x, p.y)];
   }
   [leftPath closePath];
   [leftPath fill];
}

UIImage *mask = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);

{
   CGContextClipToMask(UIGraphicsGetCurrentContext(), rect, mask.CGImage);
   [im_senza drawAtPoint:CGPointZero];
}

UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
于 2013-02-17T20:19:59.120 回答