#iOS#HeminWon

UIButton不同状态下设置背景颜色

2016-05-20  本文已影响2285人  WestMountain
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:@"'"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"'"] forState:UIControlStateSelected];
//然而系统提供的方法只能从图片获取颜色
//介绍一种方法,可以根据颜色生成图片
#pragma mark - 根据颜色获取图片
- (UIImage *)createImageWithColor:(UIColor *)color
{
    //图片尺寸
    CGRect rect = CGRectMake(0, 0, 10, 10);
    //填充画笔
    UIGraphicsBeginImageContext(rect.size);
    //根据所传颜色绘制
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    //显示区域
    CGContextFillRect(context, rect);
    // 得到图片信息
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    //消除画笔
    UIGraphicsEndImageContext();
    return image;
}

上一篇 下一篇

猜你喜欢

热点阅读