2015-05-29 85 views
10

我想用drawInRect方法調整圖片的大小,但我也想保持正確的寬高比,同時完全填充給定的框架(如.ScaleAspectFill爲UIViewContentMode所做的那樣)。 任何人都有這個準備好的答案?使用drawInRect調整圖像大小,同時保持比例方面填充的縱橫比?

這裏是我的代碼(很簡單...):

func scaled100Image() -> UIImage { 
    let newSize = CGSize(width: 100, height: 100) 
    UIGraphicsBeginImageContext(newSize) 
    self.pictures[0].drawInRect(CGRect(x: 0, y: 0, width: 100, height: 100)) 
    let newImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 
    return newImage 
} 

回答

24

OK,所以沒有現成的答案......我寫的UIImage迅速擴展,隨時如果你需要使用它它。

這就是:

extension UIImage { 
    func drawInRectAspectFill(rect: CGRect) { 
     let targetSize = rect.size 
     if targetSize == CGSizeZero { 
      return self.drawInRect(rect) 
     } 
     let widthRatio = targetSize.width/self.size.width 
     let heightRatio = targetSize.height/self.size.height 
     let scalingFactor = max(widthRatio, heightRatio) 
     let newSize = CGSize(width: self.size.width * scalingFactor, 
          height: self.size.height * scalingFactor) 
     UIGraphicsBeginImageContext(targetSize) 
     let origin = CGPoint(x: (targetSize.width - newSize.width)/2, 
          y: (targetSize.height - newSize.height)/2) 
     self.drawInRect(CGRect(origin: origin, size: newSize)) 
     let scaledImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     scaledImage.drawInRect(rect) 
    } 
} 

所以在上面的例子中,你使用它這樣的:

self.pictures[0].drawInRectAspectFill(CGRect(x: 0, y: 0, width: 100, height: 100)) 
+0

你是我的英雄 – MScottWaller

+0

對我不太好。我每次運行這個程序時都會損失40MB,並且會崩潰我的應用程序,因爲我試圖一次縮減大量照片。 – RowanPD

+0

使用比例因此圖像不模糊--UIGraphicsBeginImageContextWithOptions(targetSize,true,UIScreen.mainScreen()。scale)' –

1

Objective-C的版本,如果有人需要它(裏面粘貼此代碼UIImage的類別):

- (void) drawInRectAspectFill:(CGRect) recto { 

CGSize targetSize = recto.size; 
if (targetSize.width <= CGSizeZero.width && targetSize.height <= CGSizeZero.height) { 
    return [self drawInRect:recto]; 
} 

float widthRatio = targetSize.width/self.size.width; 
float heightRatio = targetSize.height/self.size.height; 
float scalingFactor = fmax(widthRatio, heightRatio); 
CGSize newSize = CGSizeMake(self.size.width * scalingFactor, self.size.height * scalingFactor); 

UIGraphicsBeginImageContext(targetSize); 

CGPoint origin = CGPointMake((targetSize.width-newSize.width)/2,(targetSize.height - newSize.height)/2); 

[self drawInRect:CGRectMake(origin.x, origin.y, newSize.width, newSize.height)]; 
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

[scaledImage drawInRect:recto]; 

}

相關問題