【问题标题】:Scaling view & image with UIGraphicsBeginImageContextWithOptions使用 UIGraphicsBeginImageContextWithOptions 缩放视图和图像
【发布时间】:2016-10-17 03:42:39
【问题描述】:

我正在寻找一种解决方案,将作为图像保存的 UIView(及其子视图)保存到设备照片库中。我希望输出图像的大小为 1024 x 1024。 UIView 将始终是正方形,因此子视图将适合正方形。结果保存的输出必须满足这些需求。

这是我所拥有的:

let outputSize = CGSize(width: 1024.0, height: 1024.0)

func imageWithView(view: UIView) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(outputSize, view.opaque, 0.0)
    view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: false)
    let outputImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return outputImage
}

我传递给上面参数的视图是方形视图。下面的截图是结果:

在我的故事板中,UIView 是 280x280 的正方形(如果这有区别的话)。我想要的结果是 UIView(和其中的照片)被保存为黑色框架的完整尺寸(即 1024 平方)。感谢您的帮助。

编辑

这是一个更新版本: 虽然可以满足输出 1024 平方视图的需求,但质量不是很理想。想使用这里讨论的 CGBitmapContextCreate & CGContextDrawImage 方法:http://nshipster.com/image-resizing/

func stackOverflow() -> UIImage{

    let hasAlpha = false
    let scale: CGFloat = 1.0

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(1024.0, 1024.0), !hasAlpha, scale)

    mainView.drawViewHierarchyInRect(CGRect(origin: CGPointZero, size: CGSizeMake(1024.0, 1024.0)), afterScreenUpdates:  false)

    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return scaledImage
}

【问题讨论】:

    标签: ios swift image crop


    【解决方案1】:

    你可以这样做:

    let image = UIImage(contentsOfFile: self.URL.absoluteString!)
    
    let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(0.5, 0.5))
    let hasAlpha = false
    let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
    
    UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
    image.drawInRect(CGRect(origin: CGPointZero, size: size))
    
    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    

    如图here

    【讨论】:

    • 检查我上面的编辑。我必须调整一些东西才能满足我的需求。虽然它确实将最终图像导出为 1024 平方,但图像质量并不是很理想。您提供的 NSHipster 链接看起来具有更强大的解决方案:CGBitmapContextCreate 和 CGContextDrawImage - 这将允许我使用 CGInterpolationQuality 指定质量。我很难导出 UIView 及其子视图,因为它正在寻找 CGImage 参数。您能否提供有关如何使其满足上述需求的任何提示?谢谢。
    • 实际发生了什么?您无法将 UIImage 转换为 CGImage 还是什么?您可以通过UIImage(name: "Something")?.CGImage 执行此操作,然后按照那里的其余程序进行操作。
    • 我将 UIImage 转换为 CGImage,所以工作正常。问题是将方形 UIView 合并到方法中。我认为需要将它添加到 CGContextDrawImage 或 CGBitmapCreateImage 中,但是我没有尝试任何有价值的结果。
    • func stackoverflow(view: UIView) -> UIImage{ let myView = view }
    • 我不明白你的评论是什么意思。我在上面编辑的 stackOverflow 方法有效...我只想让 CGBitmapContextCreate 和 CGContextDrawImage 版本与方形视图一起使用,因为它对图像质量有更精细的控制。
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多