简单使用 UIColor 生成 UIImage

由于种种原因,等第三方平台博客不再保证能够同步更新,欢迎移步 GitHub:https://github.com/kingcos/Perspective/。谢谢!

UIColor <-> UIImage

  • Info:
  • macOS 10.12.1
  • Xcode 8.1
  • Swift 3.0

前言

在平时的练习中,经常需要使用 UIImage,但图片又不好找。为了解决这个问题,我想到了使用 UIColor 生成 UIImage。该部分的具体知识涉及到 Core Graphics,也是一个新的知识点。在网上寻找一番,只有 Objective-C 版本,这次使用 Swift 3.0 进行重写。

Code

func generateImageWith(_ color: UIColor, andFrame frame: CGRect) -> UIImage? {
    // 开始绘图
    UIGraphicsBeginImageContext(frame.size)
    
    // 获取绘图上下文
    let context = UIGraphicsGetCurrentContext()
    // 设置填充颜色
    context?.setFillColor(color.cgColor)
    // 使用填充颜色填充区域
    context?.fill(frame)
    
    // 获取绘制的图像
    let image = UIGraphicsGetImageFromCurrentImageContext()
    
    // 结束绘图
    UIGraphicsEndImageContext()
    return image
}

使用时直接调用该方法,并传入相应参数即可,那么反过来呢?

let color = UIColor(patternImage: image!)

这样就可以从图片获取颜色。

你可能感兴趣的:(简单使用 UIColor 生成 UIImage)