将UIImage调整为100%并裁剪

时间:2016-09-28 15:23:21

标签: ios iphone swift cocoa-touch uiimage

我想要裁剪到900x900尺寸的风景UIImage

我不希望它被拉伸 - 我希望它可以缩放到100% - 图像将缩放到900x900,并且图像中超出范围的部分将被裁剪。< / p>

我已尝试过此代码:

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尺寸,这不是我想要的。

知道我能在这做什么?

由于

2 个答案:

答案 0 :(得分:1)

如果我正确地阅读了您的问题,您可以通过定制UIImageView(将图像附加到)的contentMode属性来实现您想要的效果。

在这里查看开发人员参考:https://developer.apple.com/reference/uikit/uiimageview

但是,要回答您的问题,要将图像放在UIImageView的中心而不拉伸它,请使用contentMode.center;缩放它以适应视图但保持纵横比使用.aspectFit;并且要拉伸以适合图像视图,请使用.scaleToFill。链接中解释了其他选项。

答案 1 :(得分:1)

如果图像尺寸大于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;
}

希望有所帮助

快乐的编码......

相关问题