美文网首页
根据状态设置UIButton的背景颜色

根据状态设置UIButton的背景颜色

作者: 小刘_假装是个程序员 | 来源:发表于2017-12-11 18:29 被阅读0次

    原理就是根据颜色返回一张尺寸1x1的图片然后设置为图片的背景色.

    
    [oneBtn setBackgroundImage:[Utils createImageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [oneBtn setBackgroundImage:[Utils createImageWithColor:[UIColor blueColor]] forState:UIControlStateHighlighted];
    
    
    #pragma mark - image new
    
    + (UIImage*)createImageWithColor:(UIColor*) color
    {
        CGRect rect=CGRectMake(0,0, 1, 1);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, rect);
        UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return theImage;
    }
    
    //在某个类中实现
    - (UIImage *)imageWithColor:(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 *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    
    
    

    相关文章

      网友评论

          本文标题:根据状态设置UIButton的背景颜色

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