模糊圆形rect UIBezierPath,UIButton背景

时间:2015-05-31 09:59:02

标签: ios uibutton uiimage uikit uibezierpath

我需要设置一个圆角矩形作为UIButton的背景,我需要以编程方式生成它,与颜色相关

+ (UIImage *)buttonBackgroundWithColor:(UIColor *)color {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(30.f, 30.f), NO, 1.0f);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setStroke];

    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(2.f, 2.f, 26.f, 26.f)
                                                          cornerRadius:7.f];
    CGContextSetStrokeColorWithColor(context, color.CGColor);
    bezierPath.lineWidth = 1.f;
    [bezierPath stroke];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    return [[image copy] resizableImageWithCapInsets:UIEdgeInsetsMake(10.f, 10.f, 10.f, 10.f)];
}

我试图按照此处所述https://stackoverflow.com/a/19142851/1090590

进行操作

但是,我的按钮背景是“模糊”

我做错了什么?我怎样才能让它变得清晰?

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用图层设置圆角半径

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 100,50);
[btn setTitle:@"Hello" forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor colorWithRed:128.0/255.0f green:0.0/255.0f  blue:0.0/255.0f alpha:0.7]];
btn.frame = CGRectMake(100.0, 100.0, 120.0, 50.0);//width and height should be same  value
btn.clipsToBounds = YES;

btn.layer.cornerRadius = 20;//half of the width
btn.layer.borderColor=[UIColor redColor].CGColor;
btn.layer.borderWidth=2.0f;

[self.view addSubview:btn];

答案 1 :(得分:0)

试试这个

-(void)getButtonScreenShot:(UIButton *)button{
button.layer.cornerRadius = 5.0;
button.layer.borderWidth = 2.0;
button.layer.borderColor = [UIColor blueColor].CGColor;

UIGraphicsBeginImageContext(button.frame.size);

CGContextRef  context = UIGraphicsGetCurrentContext();

[self.mybutton.layer renderInContext:context];


UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


button.layer.cornerRadius = 0;
button.layer.borderWidth = 0;
button.layer.borderColor = nil;}

cornerRadius中的更改,borderWidth和borderColor将不会反映在实际的UI按钮中。

Result

根据您的选择改变颜色