尝试从纵向模式的cgImage
获取UIImage
时,如何旋转或翻转图像。
即。如果我有案例,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)
答案 0 :(得分:1)
对于那些可能遇到类似问题的人,我发布了这个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张照片:&#34; up.JPG&#34;,&#34; down.JPG&#34;,&#34; left.JPG&#34;和&#34; right.JPG&#34;对于所有可能的相机配置,并将它们上传到游乐场的 Resources 子文件夹。逐个加载它们并检查参数发生了什么。此代码帮助我提出了工作解决方案:当图片具有.right
或.down
方向时,将仿射变换应用于裁剪矩形以获得所需的裁剪。< / p>