美文网首页#iOS#HeminWon
UIButton不同状态下设置背景颜色

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

作者: WestMountain | 来源:发表于2016-05-20 16:45 被阅读2285次
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;
}

相关文章

网友评论

    本文标题:UIButton不同状态下设置背景颜色

    本文链接:https://www.haomeiwen.com/subject/hwynrttx.html