iOS 位图图像创建——简单示例
假设我想创建一个 100 像素宽、200 像素高的图像,顶部有一个 100x100 红色正方形,底部有一个 100x100 棕色正方形 [RGB 分量 0.6、0.4、0.2]。假设我想将其作为位图,用一个直接的 C 函数为每个像素吐出组件,一次一个像素。 [有更简单的方法来创建该图像,但这里的重点是理解 iOS 位图——下次,我可能会为每个像素设置任意值。] 我该怎么做?
Say I want to create an image 100 pixels wide and 200 pixels high, with a 100x100 red square at the top and a 100x100 brown square [RGB components 0.6, 0.4, 0.2] on the bottom. And say I want to do it as a bitmap, with a straight C function spitting out the components for each pixel, one pixel at a time. [There are easier ways to create that image, but the point here is to understand iOS bitmaps -- next time, I might have arbitrary values for each pixel.] How would I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要使用的 API 已记录在 Apple 的 中CGBitmapContext 参考。
使用 CGBitmapContextCreate 从一定大小的内存块创建位图上下文
(对于 ARGB,pixelSize 通常为 4 字节)。然后,在处理像素之后,使用 CGBitmapContextCreateImage 从位图上下文创建 imageRef,您就拥有了图像。您可以将此图像分配给 CALayer 的内容以供查看,或将图像绘制在 drawRect 内。
您可以使用 C 数组语法来访问像素:
您的像素类型可以是 4 个无符号字节的 C 结构,每个字节用于 ARGB,或者只是原始字节。
The APIs you want to use are documented in Apple's CGBitmapContext Reference.
Use CGBitmapContextCreate to create a bitmap context from a block of memory of size
(pixelSize is usually 4 bytes for ARGB.) Then, after playing with the pixels, use CGBitmapContextCreateImage to create an imageRef from the bitmap context, and you have your image. You can assign this image to the contents of a CALayer for viewing, or draw the image inside a drawRect.
You can use C array syntax to access pixels:
Your pixel type can a C struct of 4 unsigned bytes, one each for ARGB, or just raw bytes.