button设置边框遇到的问题

最近有个需求,自己搞button,不用图片了

button边框的设置,貌似用UIColor转的CGColor不行,有些比如灰色直接变成透明,只能转黑色,绿色等标准色。

这里用自己的色生成CGColor了:

        CGFloat r = (CGFloat) 212/255.0;

        CGFloat g = (CGFloat) 212/255.0;

        CGFloat b = (CGFloat) 212/255.0;

        CGFloat a = (CGFloat) 1.0;

        CGFloat components[4] = {r,g,b,a};

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

        CGColorRef backgroundColor = (CGColorRef)[(id)CGColorCreate(colorSpace, components) autorelease];

        CGColorSpaceRelease(colorSpace);

        [button.layer setBorderColor:backgroundColor];

 

另外一个问题,由于没有图片,设置按下效果的时候,直接设置background不行。因此用了个曲线的方法:使用UIColor自己生成 UIImage

+ (UIImage *) createImageWithColor: (UIColor *) color

{

    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    

    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return theImage;

}

调用的时候,这样就可以了,也可以自己生成highlight的图片:      

        UIImage *img = [UIImagecreateImageWithColor:[UIColorwhiteColor]];

        [button  setBackgroundImage:img forState:UIControlStateNormal];

 

原文地址:https://www.cnblogs.com/Peterahan/p/2931953.html