2016-03-19 22 views
0

Kırpmadan sonra görüntüyü yeniden boyutlandırmak için yazdığım kod. Kırpılan görüntüyü yeniden boyutlandırmak için CGImageRef'u yeniden oluşturduğumu anladım. Bunu optimize etmenin bir yolu olmalı. Nasıl?Swift: Kırpmadan sonra görüntüyü yeniden boyutlandırmak için yazdığım kodu nasıl optimize edebilirim?

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) 
} 

cevap

0

Görüntüleri yeniden boyutlandırmak için kullanacağım bir işlev. Umarım aradığınız şeydir.

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! 
} 
İlgili konular