2016-09-29 5 views
1

CGContextDrawImageを使用するUIImageの拡張があります。 それは単に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

...それを見つけていただきありがとうございます。 – 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)) 

(希望!は、あなたの使用のために安全になります。)残念ながら、スレッドに私をリードしていない "cgcontextdrawimage swift3" で検索

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

関連する問題