[英]CGImage from portrait UIImage
试图弄清楚从人像模式下的UIImage
获取cgImage
时图像是如何旋转或翻转的。
即如果我有一种情况,其中image.size.width < image.size.height
然后调用let cg = image.cgImage!
,我得到cg.width > cg.height
(实际上, cg.width == image.size.height && cg.height == image.size.width
)。 我知道在坐标的差CGImage
和UIImage
,但我不明白-这角落UIImage
取为原点CGImage
和图像是否以某种方式翻转?
这弄乱了我的裁剪代码,我只计算UIImage
裁剪矩形,然后尝试通过调用image.cgImage!.cropping(to: rect)
裁剪图像给我意外的结果(裁剪了错误的区域)。 rect
是否需要在CGImage
的坐标系中? 我试图像这样翻转它,但它也无济于事:
swap(&croppingRect.origin.x, &croppingRect.origin.y)
swap(&croppingRect.size.width, &croppingRect.size.height)
对于那些可能像我一样遇到类似问题的人,我发布了这个Swift操场代码,该代码有助于我了解发生了什么以及如何解决它:
import UIKit
let image : UIImage = UIImage(named: "down.JPG")!
image.size
image.imageOrientation.rawValue
let center = CGPoint(x: 0.3, y: 0.3)
let kx = (center.x > 0.5 ? (1-center.x) : center.x)
let ky = (center.y > 0.5 ? (1-center.y) : center.y)
let size = CGSize(width: image.size.width*kx, height: image.size.height*ky)
// cropRect is defined in UIImage coordinate system
// it is defined as a rectangle with center in "center", with proportions
// to the original image. size of rectangle is defined by the distance from
// the center to the nearest edge divided by 2
// this was chosen due to my specific needs and can be adjusted at will
// (just don't exceed limits of the original image)
var cropRect = CGRect(x: center.x*image.size.width-size.width/2,
y: center.y*image.size.height-size.height/2,
width: size.width,
height: size.height)
cropRect
if self.imageOrientation == .right || self.imageOrientation == .down || self.imageOrientation == .left
{
let k : CGFloat = (self.imageOrientation == .right ? -1 :(self.imageOrientation == .left ? 1 : 2))
let dy = (self.imageOrientation == .right ? self.size.width : (self.imageOrientation == .left ? 0 :self.size.height))
let dx = (self.imageOrientation == .down ? self.size.width : (self.imageOrientation == .left ? self.size.height : 0))
let rotate = CGAffineTransform(rotationAngle: k*90/180*CGFloat.pi)
let translate = CGAffineTransform(translationX: dx, y: dy)
cropRect = cropRect.applying(rotate).applying(translate)
}
let cgImage = image.cgImage!
cgImage.width
cgImage.height
cropRect
let cropped = cgImage.cropping(to: cropRect)
if cropped != nil
{
cropped!.width
cropped!.height
let croppedImage = UIImage(cgImage: cropped!, scale: image.scale, orientation: image.imageOrientation)
}
拍摄4张照片:“ up.JPG”,“ down.JPG”,“ left.JPG”和“ right.JPG”,以获取所有可能的相机配置,并将其上传到游乐场的Resources子文件夹中。 一张一张地加载它们,并检查参数发生了什么。 这段代码帮助我提出了.right
解决方案: 当图像具有.right
或.down
方向时,将仿射变换应用于裁剪矩形,以获得所需的裁剪效果 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.