美文网首页iOS Developer
简单使用 UIColor 生成 UIImage

简单使用 UIColor 生成 UIImage

作者: 萌面大道 | 来源:发表于2016-10-30 00:25 被阅读532次

由于种种原因,简书等第三方平台博客不再保证能够同步更新,欢迎移步 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

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