在開發中,我們有時候需要對原始的 UIImage 進行處理,比如修改大小或者進行縮放操作。
1,擴展UIImage
這裡先對 UIImage 進行擴展,增加兩個方法,分別用於尺寸的重置和大小縮放。
import UIKit
extension UIImage {
/**
* 重設圖片大小
*/
func reSizeImage(reSize:CGSize)->UIImage {
//UIGraphicsBeginImageContext(reSize);
UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.mainScreen().scale);
self.drawInRect(CGRectMake(0, 0, reSize.width, reSize.height));
let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return reSizeImage;
}
/**
* 等比率縮放
*/
func scaleImage(scaleSize:CGFloat)->UIImage {
let reSize = CGSizeMake(self.size.width * scaleSize, self.size.height * scaleSize)
return reSizeImage(reSize)
}
}
import UIKit
class ViewController: UIViewController {
let image = UIImage(named:"img.jpg")
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
//顯示原始圖片
@IBAction func btn1Click(sender: AnyObject) {
imageView.image = image
}
//將圖片修改成指定尺寸(160*100)
@IBAction func btn2Click(sender: AnyObject) {
let reSize = CGSize(width: 240, height: 150)
imageView.image = image?.reSizeImage(reSize)
}
//將圖片縮小成原來的一半
@IBAction func btn3Click(sender: AnyObject) {
imageView.image = image?.scaleImage(0.5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}