【问题标题】:Blurred rounded rect UIBezierPath, UIButton background模糊的圆角矩形 UIBezierPath,UIButton 背景
【发布时间】:2015-05-31 09:59:02
【问题描述】:

我需要设置一个圆角矩形作为 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

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

我做错了什么?我怎样才能使它清晰易读?

【问题讨论】:

  • 使用 button.border 和 button.layer.cornerRadius = 5;
  • 我知道那个解决方案,但它对我的 UI 组件的 API 来说不是很好。
  • 我怀疑问题出在UIGraphicsBeginImageContextWithOptionsscale 参数上。将其设置为 0.0 以使其使用设备屏幕的比例因子。
  • @bobnoble 你是对的,谢谢。如果您将其移到答案部分,我会接受您的答案。

标签: ios uibutton uiimage uikit uibezierpath


【解决方案1】:

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

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];

【讨论】:

  • 我知道那个解决方案,但它对我的 UI 组件的 API 来说不是很好。最好用背景图片来做。
  • @BergP 检查这个并让我知道它是否有帮助orangejuiceliberationfront.com/…
【解决方案2】:

试试这个

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

根据你的选择改变颜色

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2012-02-13
    • 1970-01-01
    相关资源
    最近更新 更多