如何从iPhone上的UIImage获取UIColor [英] How to obtain UIColor from a UIImage on iPhone

查看:69
本文介绍了如何从iPhone上的UIImage获取UIColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想逐点处理图像,但是我不知道如何从图像中获取点的颜色.以及如何逐点移动指针?

I want to process my image point by point, but I don't know how to obtain the color of the point from the image. And how to move the pointer point by point?

推荐答案

您不能直接从UIImage进行操作,但是可以使用提供的内存缓冲区将图像渲染到位图上下文中,然后测试内存直接地. 这听起来比实际要复杂,但可能仍然比您想听的要复杂.

You can't do it directly from the UIImage, but you can render the image into a bitmap context, with a memory buffer you supply, then test the memory directly. That sounds more complex than it really is, but may still be more complex than you wanted to hear.

如果您有Erica Sadun的《 iPhone开发者的食谱》,请参阅第54页,它涵盖了该书.我会整体上推荐这本书,如果您没有它,那么值得一读.

If you have Erica Sadun's iPhone Developer's Cookbook there's good coverage of it from page 54. I'd recommend the book overall, so worth getting that if you don't have it.

我独立地获得了几乎完全相同的代码,但是遇到了一个似乎也可能出现在Sadun的代码中的错误.在pointInside方法中,point和size值是浮点数,并在转换为int之前作为浮点数相乘.如果您的坐标是谨慎的值,那很好,但是在我的情况下,我提供的是亚像素值,因此公式出现了问题.确定问题后,修复很容易,当然-在乘法之前将每个坐标转换为一个int-因此,在Sadun的情况下,它将是:

I arrived at almost exactly the same code independently, but hit one bug that it looks like may be in Sadun's code too. In the pointInside method the point and size values are floats and are multiplied together as floats before being cast to an int. This is fine if your coordinates are discreet values, but in my case I was supplying sub-pixel values, so the formula broke down. The fix is easy once you've identified the problem, of course - just cast each coordinate to an int before multiplying - so, in Sadun's case it would be:


long startByte = ((int)point.y * (int)size.width) + (int)point.x) * 4;

此外,Sadun的代码以及我自己的代码仅对alpha值感兴趣,因此我们使用仅采用alpha值的8位像素.更改CGBitMapContextCreate调用也应该允许您获得实际的颜色值(显然,如果每个像素有8位以上,则也必须将其乘以pointInside公式).

Also, Sadun's code, as well as my own, are only interested in alpha values, so we use 8 bit pixels that take the alpha value only. Changing the CGBitMapContextCreate call should allow you to get actual colour values too (obviously if you have more than 8 bits per pixel you will have to multiply that in to your pointInside formula too).

这促使我将在我的博客上进行编码(在我研究如何语法突出显示它时附带了一个小道消息):

[edit] This prompted me to put the code up on my blog (with a side-track while I worked out how to syntax highlight it):

这篇关于如何从iPhone上的UIImage获取UIColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆