利用现有的 UIView 对象直接生成 UIImage 对象

向社交媒体分享图片时经常需要将现有的视图导出为图片对象.

通过扩展方法快速生成UIImage对象

extension UIView {
    func sqiScreenshotImage(_ opaque: Bool = true) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, opaque, 0)
        if let context = UIGraphicsGetCurrentContext() {
            self.layer.render(in: context)
        }
        if let image = UIGraphicsGetImageFromCurrentImageContext() {
            UIGraphicsEndImageContext()
            return image
        }
        return nil
    }
}

UIGraphics相关方法的说明

/// Creates a bitmap-based graphics context with the specified options.(译: 使用指定的选项创建基于位图的图形上下文。)
func UIGraphicsBeginImageContextWithOptions(_ size: CGSize, _ opaque: Bool, _ scale: CGFloat)
参数size

The size (measured in points) of the new bitmap context. This represents the size of the image returned by the UIGraphicsGetImageFromCurrentImageContext() function. To get the size of the bitmap in pixels, you must multiply the width and height values by the value in the scale parameter.

译: 新位图上下文的大小(以`point`为单位)。 这表示`UIGraphicsGetImageFromCurrentImageContext()`函数返回的图像的大小。 要以像素为单位获得位图的大小,您必须将宽度和高度值乘以比例参数中的值。

官方文档说的很明白, size 指定了 context 画布的大小, 单位为 point, 如果想换算为像素, 则需要将宽高乘以最后一个参数scale.

参数opaque

A Boolean flag indicating whether the bitmap is opaque. If you know the bitmap is fully opaque, specify true to ignore the alpha channel and optimize the bitmap’s storage. Specifying false means that the bitmap must include an alpha channel to handle any partially transparent pixels.

译: 指示位图是否不透明的布尔标志。 如果您知道位图是完全不透明的,请指定 true 以忽略 Alpha 通道并优化位图的存储。 指定 false 意味着位图必须包含一个 alpha 通道来处理任何部分透明的像素。

传入true可以忽略 Alpha 通道, 优化性能; 举个例子, 如果新建一个指定宽高的 UIView 对象, 不指定颜色或者指定颜色为.clear, 则sqiScreenshotImage生成的图片为纯黑色而不是透明色, 如果想生成透明的图片, 请传入false.

参数scale

The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.

译: 应用于位图的比例因子。 如果指定值 0.0,则比例因子设置为设备主屏幕的比例因子。

通俗来讲, 这个参数, 决定了生成的图片的尺寸/宽高, 单位为像素, 值为首个参数 size * scale.


注意点

  1. 新建一个没有父视图的 UIView 对象, 调用此扩展方法, 是无法达到预期效果的;

  2. 正常展示的 UIScrollView 对象, 更新 frame 为其 contentSize 后, 使用此扩展方法截屏, 有底部黑屏现象, 将其removeFromSuperView后, 再使用, 可避免黑屏问题;

  3. 将 size 为 {100, 100}, 像素尺寸为{300, 300}的 UIImage, 转换为CGImage后, 再转换回来, 其 size 会变为{300, 300}, 所以要避免此类问题;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

依旧风轻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值