以正方形格式保存照片

时间:2019-01-21 05:18:11

标签: ios swift uiimage cgrect uigraphicscontext

我想将照片保存在完美方形的照片库中。那延伸到屏幕的整个宽度。我下面的代码将图像定位为正方形,但是我不知道如何使位置完美。我只是发布遮罩部分的代码。我没有写完整的代码。保存图像没有问题。

image

@IBAction func mask(_ sender: Any) {
    let bottomImage:UIImage = UIImage(named: "backdropd")!
    let newSize2 = CGSize(width: bottomImage.size.width, height: bottomImage.size.height)
    UIGraphicsBeginImageContextWithOptions(newSize2, false, bottomImage.scale)

    if  let rightz:UIImage = rightImage.image{
        rightz.draw(in: CGRect(x: newSize2.width * 0.125,y: newSize2.height * 0.25,width: newSize2.width/1,height:   newSize2.height/2), blendMode:CGBlendMode.normal, alpha:1.0)
    }

    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    fullImage.image = newImage
}

1 个答案:

答案 0 :(得分:0)

首先,您必须在原始图像上剪切一个正方形。假定该图像是landscape模式的图像。所以width > height。因此,最终的方形图像大小将为height * height。然后根据需要绘制背景颜色为红色的图像。

landscape图片完成了以下代码。对于potrait张图片,任务是相同的。

let image = UIImage(named: "image")!

        if image.size.width > image.size.height {
            // assuming the image is landscape one
            let sqrImgSize = image.size.height
            let extraPortion = (image.size.width - sqrImgSize) / 2
            let sqrPortionRect = CGRect(x: extraPortion,
                                        y: 0,
                                        width: sqrImgSize,
                                        height: sqrImgSize)


            // first of all, create the square image by cropping left right side out
            UIGraphicsBeginImageContextWithOptions(CGSize(width: sqrImgSize, height: sqrImgSize), false, 0.0);
            image.draw(at: CGPoint(x: -extraPortion, y: 0))

            let sqrImage = UIGraphicsGetImageFromCurrentImageContext(); // here is your center cropped image
            UIGraphicsEndImageContext();


            // now if you are interested in filling the background with red, here it is
            UIGraphicsBeginImageContextWithOptions(image.size, false, 0.0);
            let context = UIGraphicsGetCurrentContext();
            context?.beginPath()
            context?.setFillColor(UIColor.red.cgColor)
            context?.move(to: .zero)
            context?.addRect(CGRect(origin: .zero, size: image.size))
            context?.closePath()
            context?.fillPath()
            sqrImage!.draw(at: CGPoint(x: extraPortion, y: 0))
            let sqrImageWithRedBackground = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            imageView.image = sqrImageWithRedBackground
        } else {
            // do as above with slight calculation changes
        }

示例 enter image description here 此处,具有黄色背景的imageview,其中内容模式设置为高宽比。因此,由于宽高比不匹配,因此可以看到imageview的背景色。

我的输出 enter image description here

说明 显然,紫色是UIViewcontroller的{​​{1}}属性的背景色。黄色是view的背景色。红色部分是填充色,在图像的中心。

希望它能达到您的目的。

相关问题