2012-10-23 47 views
4

我想掩蓋一個UIView圖像使用它的圖層的蒙版屬性。我看到了無數的例子,說「這就是這麼簡單」。然而,經過相當多的調整後,我似乎無法重現所描述的結果。設置圖層蒙版只會使視圖消失。下面是我使用的代碼:CALayer蒙版不能正常工作

- (void)setMaskImage:(UIImage *)maskImage 
{ 
    _maskImage = maskImage; 

    self.layer.mask.contents = (__bridge id)(_maskImage.CGImage); 
} 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self != nil) { 
     self.layer.mask = [CALayer layer]; 
    } 

    return self; 
} 

- (void)setFrame:(CGRect)frame 
{ 
    [super setFrame:frame]; 

    self.layer.mask.frame = self.layer.bounds; 
} 

,這裏是我試圖用來掩蓋觀看圖片:http://cl.ly/0a300G2r133V

回答

1

以下工作:

- (void)setMaskImage:(UIImage *)maskImage 
{ 
    if (_maskView == nil) { 
     _maskView = [[UIImageView alloc] initWithImage:maskImage]; 
     _maskView.frame = self.bounds; 
     self.layer.mask = _maskView.layer; 
    } else { 
     _maskView.image = maskImage; 
    } 
} 

- (UIImage *)maskImage 
{ 
    return _maskView.image; 
} 

- (void)setBounds:(CGRect)bounds 
{ 
    [super setBounds:bounds]; 

    _maskView.frame = self.bounds; 
} 

我不知道爲什麼只用一個普通的CALayer沒有工作,但是這會增加與拉伸圖像運作良好的獎金。

6

一種可能性是,該系統實際上沒有使用setFrame:設置你的視圖的幾何。它可以使用setCenter:setBounds:。另一種可能性是系統根本沒有設置視圖的幾何圖形,並且在添加遮罩層之前,它只在調用[super initWithFrame:frame]時設置一次。

不管怎麼說,而不是覆蓋setFrame:,你應該重寫layoutSubviews

- (void)layoutSubviews { 
    [super layoutSubviews]; 
    self.layer.mask.frame = self.bounds; 
} 
+0

這是部分,但不完全是問題。 –

0

您可以覆蓋的UIView的drawRect()方法在屏幕上的自定義外觀。 嘗試使用以下方法。

//code for drawRect() 

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextAddRect(context,ImageFrame); 
CGContextClip(context); 
CGContextClearRect(context,ImageFrame); 
[super drawRect:rect]; 

它會使你的視圖在你的imageFrame區域透明。如預期