2016-09-29 436 views
1

我有一个UIImage扩展名,它使用CGContextDrawImage。 它只是旋转一个UIImage。 我更新到Xcode8和Swift3,无法弄清楚如何使用CGContextDrawImage如何在Swift 3中使用CGContextDrawImage?

我在CGContextDrawImage上出错。

CGImage.Type“无法将类型的价值 “的预期参数类型”

我的代码是 'CGImage?':

CGContextDrawImage(bitmap, CGRectMake(-size.width/2, -size.height/2, size.width, size.height), CGImage) 

和全扩展:

extension UIImage { 
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage { 
    let radiansToDegrees: (CGFloat) -> CGFloat = { 
     return $0 * (180.0/CGFloat(M_PI)) 
    } 
    let degreesToRadians: (CGFloat) -> CGFloat = { 
     return $0/180.0 * CGFloat(M_PI) 
    } 

    // calculate the size of the rotated view's containing box for our drawing space 
    let rectZero = CGPoint(dictionaryRepresentation: CGRect.zero as! CFDictionary) 
    let rotatedViewBox = UIView(frame: CGRect(origin: rectZero!, size: size)) 
    let t = CGAffineTransform(rotationAngle: degreesToRadians(degrees)); 
    rotatedViewBox.transform = t 
    let rotatedSize = rotatedViewBox.frame.size 

    // Create the bitmap context 
    UIGraphicsBeginImageContext(rotatedSize) 
    let bitmap = UIGraphicsGetCurrentContext() 

    // Move the origin to the middle of the image so we will rotate and scale around the center. 
    bitmap!.translateBy(x: rotatedSize.width/2.0, y: rotatedSize.height/2.0); 

    // // Rotate the image context 
    bitmap!.rotate(by: degreesToRadians(degrees)); 

    // Now, draw the rotated/scaled image into the context 
    var yFlip: CGFloat 

    if(flip){ 
     yFlip = CGFloat(-1.0) 
    } else { 
     yFlip = CGFloat(1.0) 
    } 

    bitmap!.scaleBy(x: yFlip, y: -1.0) 

    CGContextDrawImage(bitmap, CGRectMake(-size.width/2, -size.height/2, size.width, size.height), CGImage) 

    let newImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

    return newImage! 
} 
} 
+0

与 “cgcontextdrawimage swift3” 不幸的是搜索不会导致我的线程...感谢您找到它! – OOPer

回答

5

在Swift 3中,许多CGContext的函数都作为的实例方法导入,物业名称CGImage已更名为cgImage。并删除CGRectMake

试试这个:

bitmap!.draw(cgImage!, in: CGRect(x: -size.width/2, y: -size.height/2, width: size.width, height: size.height)) 

(希望!将是您的使用安全。)

func draw(CGImage, in: CGRect, byTiling: Bool)

相关问题