UIButton半透明边框

时间:2014-10-07 02:48:47

标签: ios cocoa-touch uibutton uikit

我有一个自定义按钮,边框应该是半透明的白色。

如果我这样做:

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

边框是半透明的,但是按钮的颜色。

3 个答案:

答案 0 :(得分: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和sublayer的背景颜色。在这种情况下,根本需要使用边框。

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

答案 1 :(得分:0)

您是否尝试过以下内容:

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

更简单的方法是通过选择按钮在Interface Builder中设置颜色,然后在Attributes Inspector中选择alpha和背景颜色:

enter image description here

答案 2 :(得分: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