我想在照片库中保存一张完美正方形的照片。这延伸到屏幕的整个宽度。我下面的代码将图像定位在正方形中,但我不知道如何使位置完美。我只是发布面具部分的代码。我没有把我的整个代码。我在保存图像时没有问题。
@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
}
首先,您必须从原始图像中切出一个正方形。假设图像是 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
}
示例 这里是带有黄色背景的 ImageView ,其中内容模式设置为宽高比合适。所以 ImageView 的背景颜色是可见的,因为纵横比不匹配。
说明
很明显,紫色是 UIViewcontroller
的 view
属性的背景色。黄色是 UIImageView
的背景色。红色部分是填充颜色,位于图像中心。
希望它能达到你的目的。
关于ios - 以方形格式保存照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283847/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) | Powered by Discuz! X3.4 |