【问题标题】:In this CGBitmapContextCreate, why is bytesPerRow 0?在这个 CGBitmapContextCreate 中,为什么 bytesPerRow 是 0?
【发布时间】:2011-06-23 15:39:02
【问题描述】:

我注意到在 Apple 的示例代码中,他们经常在 CGBitmapContextCreate 的 bytesPerRow 参数中提供值 0。例如,这来自 Reflection 示例项目。

CGContextRef gradientBitmapContext = CGBitmapContextCreate(NULL, pixelsWide, pixelsHigh,  
                                                            8, 0, colorSpace, kCGImageAlphaNone);

这对我来说似乎很奇怪,因为我总是采用将图像宽度乘以每个像素的字节数的方法。我尝试将零换成我自己的代码并进行测试。果然,它仍然有效。

size_t bitsPerComponent = 8;
size_t bytesPerPixel = 4;
size_t bytesPerRow = reflectionWidth * bytesPerPixel;   

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,
                                             reflectionWidth,
                                             reflectionHeight,
                                             bitsPerComponent,
                                             0, // bytesPerRow ??
                                             colorSpace,
                                             kCGImageAlphaPremultipliedLast);

根据文档,bytesPerRow 应该是“位图每行使用的内存字节数。”

那么交易是什么?我什么时候可以提供零,什么时候必须计算确切的值?以一种或另一种方式执行此操作是否会对性能产生影响?

【问题讨论】:

  • 您发布的示例:CGBitmapContextCreate(NULL, pixelWide, pixelHigh, 8,0,colorSpace,kCGImageAlphaNone);无效。你不能在没有 Alpha 通道的情况下创建位图上下文。
  • btw--如果您查看应用程序的日志输出(您可能需要检查 Console.app 中的系统日志)CGBitmapContextCreate 将在您尝试创建位图时打印一条错误消息带有无效参数的上下文。

标签: objective-c ios core-graphics


【解决方案1】:

我的理解是,如果你传入零,它会根据 bitsPerComponent 和 width 参数计算每行的字节数。您可能希望在每行字节的末尾添加额外的填充(如果您的设备需要它,或其他一些约束)。在这种情况下,您可以传递的值不仅仅是宽度 *(每像素字节数)。我想这在现代 i/MacOS 开发中可能永远不需要,除了一些奇怪的边缘情况优化。

【讨论】:

  • 听起来很合理。如果 Apple 在某个地方的文档中澄清了这一点,那就太好了(如果它在那里,我无法找到它)。我发现过于依赖无证行为有点令人不安。
  • bytesPerRow 位图每行使用的内存字节数。如果 data 参数为 NULL,则传递值 0 会导致自动计算该值。
  • 我想我会在这里添加这个(来自 CGBitmapContext 标头):“每个像素的字节数等于 (bitsPerComponent * number of components + 7)/8'. Each row of the bitmap consists of bytesPerRow' 字节,必须至少为 width * bytes per pixel' bytes; in addition, bytesPerRow' 必须是每像素字节数的整数倍。"
  • @chrisp 你能解释一下组件的数量吗?
猜你喜欢
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 2012-12-05
  • 1970-01-01
  • 2018-01-15
  • 2021-07-02
  • 2014-02-18
相关资源
最近更新 更多