美文网首页
iOS开发将颜色(UIColor)转为图片(UIImage)

iOS开发将颜色(UIColor)转为图片(UIImage)

作者: HarveyCC | 来源:发表于2018-10-22 22:21 被阅读13次

    Objective-c 版本

    - (nullable UIImage *)imageFromColor: (nonnull UIColor *)color withSize:(CGSize)size {
        
        CGRect rect = CGRectMake(0, 0, size.width, size.height);
        
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context,color.CGColor);
        CGContextFillRect(context, rect);
        
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return image;
    }
    

    Swift 版本

    extension UIColor {
        
        func asImage(_ size: CGSize) -> UIImage? {
            
            var resultImage: UIImage? = nil
            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
            
            guard let context = UIGraphicsGetCurrentContext() else {
                
                return resultImage
            }
            
            context.setFillColor(self.cgColor)
            context.fill(rect)
            resultImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            return resultImage
        }
    }
    

    使用

    let colorImage = UIColor.black.asImage(CGSize(width: 100, height: 100));
    

    相关文章

      网友评论

          本文标题:iOS开发将颜色(UIColor)转为图片(UIImage)

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