iOS - Calculating percent of a color in an area

2019-06-14 04:26发布

问题:

I may not always understand every function in an API but usually I can at least get started on a problem. This time I don't even know if this is possible or how to attack it....

I have an area on the screen that a user can draw. This works fine. They draw with three different colors indicating three different cases. I need to detect the percent coverage of the three different colors in the area. There does not seem to be any way to get the color value of a single screen pixel. How would you approach this?

回答1:

You can do this by creating a bitmap graphics context with a block of memory that you allocate and pass to CGBitmapContextCreate.

Then you can simply draw your view or image into that context (e.g. using the CALayer method renderInContext:). The block of memory that you allocated will then contain the pixel data of what you have drawn into the context. The byte order depends on the options you specified when creating the context, usually it'll be RGBA (one byte for red, the next for green, etc.).