[英]Resize UIImage to 100% and crop
我有一個風景UIImage
,我想裁剪為900x900大小。
我不希望將其拉伸-我希望將其縮放到100%-圖像將被縮放以適合900x900,並且圖像的超出范圍的部分將被裁剪。
我已經試過這段代碼:
UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.main.scale);
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage!
但是,它所做的只是拉伸圖像以適合900x900尺寸,這不是我想要的。
知道我該怎么辦嗎?
謝謝
如果我正確地閱讀了您的問題,則可以通過定制UIImageView的contentMode屬性(將圖像附加到該屬性)來實現所需的功能。
在這里查看開發人員參考: https : //developer.apple.com/reference/uikit/uiimageview
但是,要回答您的問題,請將圖像放置在UIImageView的中心而不拉伸它,請使用contentMode.center; 縮放它以適合視圖,但使用.aspectFit保持長寬比; 並拉伸以適合圖像視圖,請使用.scaleToFill。 鏈接中還介紹了其他選項。
如果圖像尺寸大於900,則可以從圖像中心裁剪到900像素。
這是代碼:
func centerCropImage(image1:UIImage) -> UIImage
{
let modifiedSize:CGFloat = 900.0;
// Center the crop area
let clippedRect = CGRect(x: ((image.size.width - modifiedSize)/2), y: ((image.size.height - modifiedSize)/2), width: modifiedSize, height: modifiedSize);
// Crop logic
let imageRef:CGImage = image.cgImage!.cropping(to: clippedRect)!;
//(image as! CGImage).cropping(to: clippedRect)!;
let croppedImage = UIImage(cgImage: imageRef);
return croppedImage;
}
希望能幫助到你
快樂的編碼...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.