CGImageSourceCreateImageAtIndex是否始终返回Up方向的CGImage?文档有无说明?
CGImageSourceCreateImageAtIndex 图片方向问题的官方说明
嘿,这个问题我之前帮不少开发者理清过,苹果官方文档里确实明确说明了CGImageSourceCreateImageAtIndex的这个行为:
- 它不会自动应用图片元数据里的
kCGImagePropertyOrientation方向信息,返回的CGImage始终是原始像素数据的方向(也就是你看到的Up方向)。这个方向元数据只是作为“描述信息”存在,并不会直接修改像素排列。 - 那这个方向属性的作用是什么呢?它是给后续的渲染或处理流程提供参考的——比如当你用
UIImage初始化这个CGImage时,UIImage会读取这个方向值,然后在绘制到屏幕上时自动调整显示方向;如果你需要自己处理方向,就得手动根据这个值对CGImage做旋转、翻转的变换。
苹果Core Graphics官方文档里的原话是这样的:
CGImageSourceCreateImageAtIndexcreates a CGImage object from the image data at the specified index. The image returned does not apply orientation information stored in the image source. To apply orientation, you must use the orientation information to transform the image yourself, or use an API likeUIImagethat applies orientation automatically.
如果你的需求是得到已经应用了正确方向的CGImage,这里有两个常用的实践方案:
- 借助
UIImage中转:先创建带方向的UIImage,再通过绘制上下文把它转换成调整后的CGImage(注意直接取UIImage.cgImage还是原始方向,必须手动绘制); - 手动计算变换矩阵:根据
kCGImagePropertyOrientation的枚举值,生成对应的仿射变换矩阵,对原始CGImage做变换后生成新的CGImage。
内容的提问来源于stack exchange,提问作者an0
相关产品推荐
相关产品推荐

