You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 中如何不依赖 UIKit 创建空白带色 CGImage 画布

纯Core Graphics实现黑色空白CGImage方案

无需依赖UIKit,通过CGBitmapContext创建画布再导出CGImage的方式最稳妥,避免手动配置CGBitmapInfo、CGDataProvider的复杂逻辑,同时兼容所有Apple平台。

完整实现代码

func createBlackCGImage(width: Int, height: Int) -> CGImage? {
    // 使用SRGB色彩空间,适配绝大多数场景
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    // 配置位图格式:RGBA8位,alpha通道预乘在末尾
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
    // 单像素4字节,计算每行数据长度
    let bytesPerRow = width * 4

    // 创建位图上下文,data传nil由系统自动分配管理内存
    guard let context = CGContext(
        data: nil,
        width: width,
        height: height,
        bitsPerComponent: 8,
        bytesPerRow: bytesPerRow,
        space: colorSpace,
        bitmapInfo: bitmapInfo.rawValue
    ) else {
        return nil
    }

    // 填充全黑背景
    context.setFillColor(red: 0, green: 0, blue: 0, alpha: 1)
    context.fill(CGRect(x: 0, y: 0, width: width, height: height))

    // 后续绘制线条的逻辑可在这里直接操作context

    // 导出生成CGImage
    return context.makeImage()
}

参数说明

  • 不需要alpha通道时,可将CGImageAlphaInfo.premultipliedLast替换为CGImageAlphaInfo.noneSkipLast,减少内存占用提升绘制性能
  • 生成的context可直接用于后续线条绘制,无需额外创建画布

如果你坚持要直接调用CGImage.init构造方法实现,需要先手动分配一块全零的内存数据(对应纯黑像素值),再封装为CGDataProvider传入,需要自行处理内存释放逻辑,不如CGBitmapContext方案简洁安全。

内容的提问来源于stack exchange,提问作者Felipe Arrudi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:39:03