在核心图形中反转径向渐变蒙版

时间:2013-07-07 12:45:36

标签: ios core-graphics gradient masking

我能够使用核心图形在iOS中屏蔽具有黑/白色径向渐变的图片。但我得到的结果恰恰相反。我希望图片在应用渐变的区域是透明的,并且应该显示图片的剩余部分。这意味着图片中有“![hole] [1]”。但是这里的洞将由渐变蒙版创建。

任何人都可以建议我使用某种方式或任何提示来反转径向渐变蒙版,就像我们在photoshop中所做的那样。

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是插入图层,而不是使用蒙版。这就是我为我的IOS应用所做的。

- (void) addSublayer {
    CGPoint center = CGPointMake(self.addButton.frame.origin.x, self.addButton.frame.origin.y);
    UIBezierPath* clip = [UIBezierPath bezierPathWithArcCenter:center
                                                    radius:CGRectGetMaxX(self.addUnavailabilitySubView.frame) - self.addButton.center.x
                                                startAngle:-1.57
                                                  endAngle:1.57
                                                 clockwise:YES];
    [clip addLineToPoint:center];
    [clip closePath];

    CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
    [shapeLayer setMasksToBounds:YES];
    shapeLayer.frame = self.view.layer.bounds;
    shapeLayer.path = clip.CGPath;

    //This gradient layer can be a customised one
    CALayer *gradientLayer = [CALayer layer];
    gradientLayer.frame = CGRectMake(0, 0, self.view.bounds.size.height, self.view.bounds.size.width);

    [self.view.layer insertSublayer:gradientLayer atIndex:0];
}

我也可以在这里分享我的径向渐变图层:)

-(void)drawInContext:(CGContextRef)ctx {
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 }; // End color

    CGFloat components[8] = {0.f, 0.f, 0.f, 0.3f, 0.f, 0.f, 0.f, 0.8f};

    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, num_locations);

    CGFloat myStartRadius, myEndRadius;

    CGPoint radialCenter = CGPointMake(100, 100)
    myStartRadius = 20;
    myEndRadius = 300;
    CGContextDrawRadialGradient (ctx, gradient, radialCenter,
                             myStartRadius, radialCenter, myEndRadius,
                             kCGGradientDrawsAfterEndLocation);
}