search

Home  >  Q&A  >  body text

ios - Swift 函数代码求讲解每句的意思

func coloredImage(image: UIImage, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIImage! {
    let rect = CGRect(origin: CGPointZero, size: image.size)
    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    let context = UIGraphicsGetCurrentContext()
    image.drawInRect(rect)
    CGContextSetRGBFillColor(context, red, green, blue, alpha)
    CGContextSetBlendMode(context, CGBlendMode.SourceAtop)
    CGContextFillRect(context, rect)
    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return result
}

主要是不太明白这些UI和CG函数的意思,求大神讲解下

PHP中文网PHP中文网2810 days ago409

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:36:29

    
    /**
     - parameter image: 参数,图片对象
     - parameter red:   RGB颜色 R
     - parameter green: RGB颜色 G
     - parameter blue:  RGB颜色 B
     - parameter alpha: 透明度
     
     - returns: 返回一个图片对象
     */
    func coloredImage(image: UIImage, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIImage! {
        //结构体:大小是 参数图片大小,位置是 零
        let rect = CGRect(origin: CGPointZero, size: image.size)
        //开启位图上下文,根据图片的大小,这个方法和后面的“UIGraphicsEndImageContext”呼应,一个开启一个关闭
        UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
        //获取当前绘图上下文
        let context = UIGraphicsGetCurrentContext()
        //将图片渲染到该上下文中
        image.drawInRect(rect)
        //设置上下文的颜色为传进来参数的颜色,填充色
        CGContextSetRGBFillColor(context, red, green, blue, alpha)
        //设置组合模式,通过“Overlay”“Lighten”... 几种模式自己试试吧!可以看到效果
        CGContextSetBlendMode(context, CGBlendMode.Overlay)
        //通过上下文“context”绘制一个矩形
        CGContextFillRect(context, rect)
        //从当前的上下文中获取图片对象
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回图片对象
        return result
    }
    
    //: 这是演示效果的demo,我是在playground中写的
    
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    view.backgroundColor = UIColor.yellowColor()
    
    var img = UIImage(named:"QQ20160227-0@2x.png")
    img = coloredImage(img!, red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
    
    let imgView = UIImageView(image: img)
    
    view.addSubview(imgView)
    


    reply
    0
  • 迷茫

    迷茫2017-04-17 17:36:29

    Just check the function manual for this kind of problem
    The content at the beginning of UI is from the UIKit library, which is the iOS control library UIKit库 这是iOS控件库
    CG开头是来自 Core GraphicThe content at the beginning of CG is from the Core Graphic library, which is 2D Drawing library

    reply
    0
  • Cancelreply