0

我正在尝试将图像裁剪为不规则形状,但我需要使被移除的区域透明。

UIView 的内部子类

   CALayer *myLayer = [CALayer layer];
   CAShapeLayer *mask = [CAShapeLayer layer];    
    myLayer.frame = self.bounds;
    myLayer.contents =  (id)[self.picture CGImage];
    mask.path = path;
    myLayer.mask = mask;
    [self.layer addSublayer:myLayer];

这将适当地裁剪图像,但视图的背景颜色是白色的,因此仍然可见。我试过让其他图层透明,但没有奏效。

(self 和 subview 都指同一个视图)

[self layer].backgroundColor = [UIColor clearColor].CGColor //no change
[self layer].opacity = 0; //makes entire view transparent
subView.backgroundColor = [UIColor clearColor]; // entire view becomes transparent

是否可以创建我想要达到的效果?

4

1 回答 1

0

我尝试了同样的事情,这是确切的代码:

// In KMViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];
    CGRect frame = CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
    KMView *view = [[KMView alloc] initWithFrame:frame];
    view.center = self.view.center;
    [self.view addSubview:view];
}

// In KMView.m
- (id)initWithFrame:(CGRect)frame
 {
    self = [super initWithFrame:frame];
    if (self) {
        // self.backgroundColor = [UIColor clearColor];
        CALayer *layer = [CALayer layer];
        CAShapeLayer *mask = [CAShapeLayer layer];
        layer.frame = self.bounds;
        UIImage *image = [UIImage imageNamed:@"orange"];
        layer.contents = (id)image.CGImage;
        CGPathRef path = CGPathCreateWithEllipseInRect(frame, NULL);
        mask.path = path;
        CGPathRelease(path);
        layer.mask = mask;
        [self.layer addSublayer:layer];
    }
    return self;
}

它按预期对我有用。背景是透明的。然后我尝试添加

self.backgroundColor = [UIColor clearColor];

到代码的开头并没有任何改变,图像显示在剪切到路径的透明背景上。

我认为问题可能出在其他地方。

苹果手机

于 2013-04-27T10:25:46.943 回答