2016-03-19 13 views
0

ここでは、クロップ後にイメージのサイズを変更するためのコードを示します。私はCGImageRefを作り直して、切り取った画像のサイズを変更することがわかりました。私はそれを最適化する方法がなければならないと思う。それで?Swift:トリミング後にイメージのサイズを変更するために書いたコードを最適化する方法は?

let imgRef: CGImageRef = CGImageCreateWithImageInRect(img.CGImage, rect)! 
let croppedImg = UIImage(CGImage: imgRef, scale: 1, orientation: .Up) 

let imgSize = CGSize(width: Conf.Size.avatarSize.width, height: Conf.Size.avatarSize.width) 

UIGraphicsBeginImageContextWithOptions(imgSize, false, 1.0) 
croppedImg.drawInRect(CGRect(origin: CGPointZero, size: imgSize)) 
let savingImgContext = UIGraphicsGetCurrentContext() 
UIGraphicsEndImageContext() 

if let savingImgRef: CGImageRef = CGBitmapContextCreateImage(savingImgContext) { 
    let savingImg = UIImage(CGImage: savingImgRef, scale: 1, orientation: .Up) 
    UIImageWriteToSavedPhotosAlbum(savingImg, nil, nil, nil) 
} 

答えて

0

ここでは、画像のサイズを変更するための関数です。うまくいけばそれはあなたが探しているものです。

func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage { 
    let size = image.size 

    let widthRatio = targetSize.width/image.size.width 
    let heightRatio = targetSize.height/image.size.height 

    // Figure out orientation 
    var newSize: CGSize 
    if(widthRatio > heightRatio) { 
     newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) 
    } else { 
     newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) 
    } 

    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) 

    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) 
    image.draw(in: rect) 
    let newImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

    return newImage! 
} 
関連する問題