Leo*_*ien 5 flip orientation uiimage ios swift
如何垂直(向上/向下)翻转 UIImage?这是之前问过的问题...
我在图像视图中显示图像,并且可以在图像中绘制。对于擦除功能,我在 CAShapeLayer 中使用了 UIBezierpath。CAShapeLayer 的strokeColor 是UIColor(patternImage: background).cgColor,其中background 是与image view 中的图片相同的图片。背景竟然是颠倒的。从其他 Stackoverflow 帖子中我了解到这是因为 UIKit 和 Core Graphics 为其坐标系统使用了另一个原点。
我尝试了 Stackoverflow 帖子中的一些解决方案来翻转我的背景图像。这些都没有工作:
UIImage* sourceImage = [UIImage imageNamed:@"whatever.png"];
UIImage* flippedImage = [UIImage imageWithCGImage:sourceImage.CGImage
scale:sourceImage.scale
orientation:UIImageOrientationUpMirrored];
Run Code Online (Sandbox Code Playgroud)
let ciimage: CIImage = CIImage(CGImage: imagenInicial.CGImage!)
let rotada3 = ciimage.imageByApplyingTransform(CGAffineTransformMakeScale(1, -1))
Run Code Online (Sandbox Code Playgroud)
func flipImageVertically() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let bitmap = UIGraphicsGetCurrentContext()!
bitmap.translateBy(x: size.width / 2, y: size.height / 2)
bitmap.scaleBy(x: 1.0, y: -1.0)
bitmap.translateBy(x: -size.width / 2, y: -size.height / 2)
bitmap.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
Run Code Online (Sandbox Code Playgroud)
我开始通过改变比例并观察结果来试验最后一个解决方案。原来我的解决方案是我需要使用
bitmap.scaleBy(x: 1.0, y: 1.0)
Run Code Online (Sandbox Code Playgroud)
在函数 flipImageVertically() 中创建一个新的颠倒图像。
我不明白这个。通过缩放 1 我以为我没有改变任何东西。我不知道我的原始图像的 imageOrientation 是否重要。但是 imageOrientation 是 .up。
我希望有人可以解释为什么我可以使用该功能垂直翻转图像
func flipImageVertically() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let bitmap = UIGraphicsGetCurrentContext()!
bitmap.translateBy(x: size.width / 2, y: size.height / 2)
bitmap.scaleBy(x: 1.0, y: 1.0)
bitmap.translateBy(x: -size.width / 2, y: -size.height / 2)
bitmap.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
Run Code Online (Sandbox Code Playgroud)
我认为重点是您要获取上下文UIGraphicsGetCurrentContext(),然后使用该draw(_:CGImage, in: CGRect)函数进行绘图。
事实上,您可以安全地删除代码中的这些行,因为它们根本不执行任何操作:
bitmap.translateBy(x: size.width / 2, y: size.height / 2)
bitmap.scaleBy(x: 1.0, y: 1.0)
bitmap.translateBy(x: -size.width / 2, y: -size.height / 2)
Run Code Online (Sandbox Code Playgroud)
我的意思是...您正在按 1.0 缩放(这什么也没做),并且您正在以相反的方向将上下文翻译相同的量,这意味着您根本没有翻译。
如果您使用 UIImage 实例方法绘制到上下文draw(in: CGRect),则图像不会翻转。
| 归档时间: |
|
| 查看次数: |
3025 次 |
| 最近记录: |