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

iOS截图去除状态栏:裁剪逻辑异常求助

问题分析与解决

你的问题出在UIImage的逻辑尺寸和CGImage的像素尺寸不匹配上:

  • UIImage的size是逻辑坐标(和屏幕点对应),而cgImage的尺寸是像素坐标,两者的换算关系是 像素尺寸 = 逻辑尺寸 × image.scale。
  • 你直接用逻辑值44计算裁剪区域,相当于在像素层面只裁剪了44/scale的高度,导致实际裁剪区域远小于预期,最终只得到左上角一小块图片。

修正后的代码

extension UIImage {
    class func removeStatusbarFromScreenshot(_ screenshot: UIImage) -> UIImage {
        // 状态栏逻辑高度(iPhone非全面屏为20,全面屏为44,可根据需求调整)
        let statusBarHeight: CGFloat = 44.0
        let scale = screenshot.scale
        
        // 将逻辑尺寸转换为像素尺寸
        let statusBarPixelHeight = statusBarHeight * scale
        let originalPixelWidth = screenshot.size.width * scale
        let originalPixelHeight = screenshot.size.height * scale
        
        let newPixelHeight = originalPixelHeight - statusBarPixelHeight
        let cropRect = CGRect(
            x: 0,
            y: statusBarPixelHeight,
            width: originalPixelWidth,
            height: newPixelHeight
        )
        
        guard let imageRef = screenshot.cgImage?.cropping(to: cropRect) else {
            return screenshot // 裁剪失败返回原图片,避免崩溃
        }
        
        // 创建新UIImage时指定原scale和orientation,保证显示正确
        return UIImage(cgImage: imageRef, scale: scale, orientation: screenshot.imageOrientation)
    }
}

关键改动说明

  • 引入screenshot.scale,把所有逻辑尺寸转换成像素尺寸后再计算裁剪区域
  • 创建新UIImage时指定原图片的scale和orientation,避免图片显示时出现拉伸或方向错误
  • 增加可选绑定处理cgImage为空的情况,避免强制解包崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:05:32