2013-02-15 70 views
2

我需要一個來自Masked CALayer的UIImage。這是我使用的功能:來自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,結果是正確的,但如果我嘗試獲取相對於該層的圖像,面具丟失。

+0

的可能重複[layer.renderInContext不layer.mask考慮?](http://stackoverflow.com/questions/4896296/layer-renderincontext-doesnt-take-layer-mask-into -帳戶) – 2013-04-08 10:51:58

回答

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();