Swift图片原色渲染

public class HuaUtilitityImage: NSObject {

  // 普通渲染
  public func renderingImageWithTintColor(image: UIImage?,_ tintColor: UIColor) -> UIImage?{
    return renderingImageWithThintColor(image, tintColor, CGBlendMode.DestinationIn)
  }
  // 渐变渲染
  public func renderingImageWithGradientThintColor(image: UIImage?,_ tintColor: UIColor) -> UIImage?{
    return renderingImageWithThintColor(image, tintColor, CGBlendMode.Overlay)
  }
  // 渲染(图片UIImage,渲染颜色,渲染模式)
  public func renderingImageWithThintColor(image: UIImage?,_ tintColor: UIColor,_ blendMode: CGBlendMode) -> UIImage?{
    if image == nil{
      return nil
    }
    UIGraphicsBeginImageContextWithOptions(image!.size, false, 0.0)//初始化绘图上下文[绘图大小,不透明性,缩放比]
    tintColor.setFill()//设置填充颜色到绘图上下文
    let bounds = CGRectMake(0, 0, image!.size.width, image!.size.height)//绘图边界
    UIRectFill(bounds)//填充颜色
    image!.drawInRect(bounds, blendMode: blendMode, alpha: 1.0)//绘制图片
    if blendMode != CGBlendMode.DestinationIn {//渐变绘制
      image!.drawInRect(bounds, blendMode: CGBlendMode.DestinationIn, alpha: 1.0)
    }
    let tintedImage = UIGraphicsGetImageFromCurrentImageContext()//取回上下文图片
    UIGraphicsEndImageContext()//结束绘图上下文
    return tintedImage
  }
  // 渲染后的图片还有可能被系统上下文渲染器自动渲染,所以要根据不同情况进行是否取消系统自动渲染
  public func translateRenderingModeImage(image:UIImage?,_ renderingMode:UIImageRenderingMode) -> UIImage?{
    if image == nil{
      return nil
  }
  //UIImageRenderingMode.Automatic 设置根据系统上下文自动判断是否被系统渲染,可能原色/可能被渲染[默认]
  //UIImageRenderingMode.AlwaysOriginal 一直保持原来的颜色,不被系统自动渲染[不作为渲染模板]
  //UIImageRenderingMode.AlwaysTemplate 一直保持为渲染模板色被渲染
  return image?.imageWithRenderingMode(renderingMode)
}
  // 普通渲染原色模式
  public func renderingImageForNavigation(image: UIImage,_ color:UIColor) -> UIImage{
    return translateRenderingModeImage(renderingImageWithTintColor(image, color), UIImageRenderingMode.AlwaysOriginal)!
  }
  // 设置UIImageView圆角
  public func setImageViewCornerRadius(imageView:UIImageView?, radio:Int){
    imageView?.layer.cornerRadius = CGFloat(radio)
    imageView?.layer.masksToBounds = true
  }
}

 

以下是简单地调用:

@IBOutlet weak var imageRending: UIImageView!
override func viewDidLoad() {
  super.viewDidLoad()
  let image = UIImage(named: "bookImage")
  imageRending.image = HuaUtilitityImage().renderingImageForNavigation(image!, UIColor.greenColor())

}

转载于:https://www.cnblogs.com/huaxianglala/p/6115967.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值