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

1.OC版本

- (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;

}

2.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));

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容