【问题标题】:iPhone: how to create an empty bitmap in memory?iPhone:如何在内存中创建一个空位图?
【发布时间】:2011-05-16 17:27:09
【问题描述】:

我需要创建一个具有已知宽度和高度值的空位图(在内存中)。 我将使用此位图的上下文来绘制图像,然后在 MKOverlayVew 上显示图像。 有谁知道最简单的方法吗?

【问题讨论】:

  • 空的和透明的一样吗?还是“空”如填充了一些背景颜色(黑色、白色等)?

标签: iphone


【解决方案1】:

下面的代码应该可以解决问题。原文来自:CGBitmapContextCreate on the iPhone/iPad

      int width = 500;
      int height = 500;

      CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
      unsigned char *rawData = malloc(height * width * 4);
      memset(rawData, 0, height * width * 4);

      NSUInteger bytesPerPixel = 4;
      NSUInteger bytesPerRow = bytesPerPixel * width;
      NSUInteger bitsPerComponent = 8;
      CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
      // Do your thing and then release
      CGColorSpaceRelease(colorSpace);
      free(rawData);
      CGContextRelease(context);

我不确定该问题上发布的代码是否有任何区别,但 OP 提到了内存问题,而我发布的这段代码从未有过任何差异。

【讨论】:

  • 谢谢!这段代码确实有效。并且工作良好。结果,我的应用程序的性能提高了大约 100 倍。
  • 一旦你调用了 CGBitmapContextCreate,你还能通过写入 inte rawData 内存来修改像素吗?
猜你喜欢
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
相关资源
最近更新 更多