2014-10-07 201 views
1

我有一個自定義按鈕,邊框應該是半透明的白色。UIButton半透明邊框

如果我這樣做:

- (void) awakeFromNib {   
    self.layer.cornerRadius = 6.0f; 
    self.layer.borderWidth = 4.0f; 
    self.layer.borderColor = [[UIColor colorWithWhite:1.0f alpha:0.5f] CGColor]; 
} 

我得到這個 - 透明度,但原來的按鈕顏色:

enter image description here

邊框是半透明的,但按鈕的顏色。

回答

2

將子圖層的顏色設置爲想要按鈕的顏色(不要設置按鈕本身的背景顏色),並將其矩形插入到按鈕的矩形中,

- (void) awakeFromNib { 
    self.layer.cornerRadius = 6.0f; 
    self.layer.borderWidth = 4.0f; 
    self.layer.borderColor = [[UIColor colorWithWhite:1.0f alpha:0.5f] CGColor]; 
    CALayer *sub = [CALayer new]; 
    sub.frame = CGRectInset(self.bounds, 4, 4); 
    sub.backgroundColor = [UIColor redColor].CGColor; 
    [self.layer addSublayer:sub]; 
} 

enter image description here

另一種方式來做到這一點,如果你想要的背景顏色過於圓潤,這將更好地工作,是用背景色self.layer和子層兩者。在這種情況下,所有人都需要使用邊框。

- (void) awakeFromNib { 
    self.layer.cornerRadius = 6.0f; 
    self.tintColor = [UIColor whiteColor]; // make white text 
    self.layer.backgroundColor = [[UIColor colorWithWhite:1.0f alpha:0.4] CGColor]; 
    CALayer *sub = [CALayer new]; 
    sub.cornerRadius = 4.0f; 
    sub.frame = CGRectInset(self.bounds, 4, 4); 
    sub.backgroundColor = [UIColor blueColor].CGColor; 
    [self.layer addSublayer:sub]; 
} 

enter image description here

0

你試過類似如下:

self.backgroundColor = [[UIColor colorWithWhite:1.0f alpha:0.5f] CGColor]; 

一種更簡單的方法是通過選擇按鈕,然後選擇在屬性檢查器中的α和背景顏色設置在界面生成器的顏色:

enter image description here

0

以防萬一,如果有人查找與透明外邊框的UIImage的。如果您只設置圖層邊框,則會獲得透明邊框,但您會在該邊框後面看到內部圖像,而不是外部圖像。我設法創建了一個帶有透明外部邊框的ImageView。

這個想法很簡單。我從UIImageView保存UIImage。然後我刪除UIImage並將初始圖層設置爲邊框圖層。然後我在它上面放置一個新的更小的子圖層,並將其保存的UIImage設置爲它的內容。

#import <UIKit/UIKit.h> 

@interface SSCircleImageView : UIImageView 


@end 

#import "SSCircleImageView.h" 



@implementation SSCircleImageView 


const CGFloat borderWidth = 5.0f; 
const CGFloat borderAlpha = 0.3f; 


- (void)awakeFromNib 
{ 
    UIImage *image = self.image; 
    self.image = nil; 

    self.clipsToBounds = YES; 
    self.layer.cornerRadius = self.frame.size.width/2.0; 
    self.layer.borderWidth = borderWidth; 
    self.layer.borderColor = [[UIColor colorWithWhite:1.0f alpha:borderAlpha] CGColor]; 

    CALayer *subLayer = [CALayer layer]; 
    subLayer.frame = CGRectInset(self.bounds, self.layer.borderWidth, self.layer.borderWidth); 
    subLayer.cornerRadius = subLayer.frame.size.width/2.0; 
    subLayer.contents = (id)image.CGImage; 
    [self.layer addSublayer:subLayer]; 
} 



@end 

它看起來像這樣: enter image description here