如何获取 UIView 中像素的颜色?
我正在尝试开发一个小型应用程序。 在其中,我需要检测 UIView 中像素的颜色。 我有一个 CGPoint 定义我需要的像素。 UIView 的颜色是使用 CoreAnimation 更改的。
我知道有一些复杂的方法可以从 UIImage 中提取颜色信息。 但是我找不到 UIViews 的解决方案。
在伪代码中,我正在寻找类似
pixel = [view getPixelAtPoint:myPoint];
UIColor *mycolor = [pixel getColor];
任何输入的东西,非常感谢。
I am trying to develop a small application. In it, I need to detect the color of a pixel within an UIView. I have a CGPoint defining the pixel I need. The colors of the UIView are changed using CoreAnimation.
I know there are some complex ways to extract color information from UIImages. However I couldn't find a solution for UIViews.
In Pseudo-Code I am looking for something like
pixel = [view getPixelAtPoint:myPoint];
UIColor *mycolor = [pixel getColor];
Any input greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是更有效的解决方案:
链接到文件: https://github.com/ivanzoid /ikit/tree/master/UIView+ColorOfPoint
Here is more efficient solution:
Link to files: https://github.com/ivanzoid/ikit/tree/master/UIView+ColorOfPoint
ivanzoid 的答案
Swift 3
Swift 2
的 swift 化版本,基于底层
CALayer
,但易于翻译返回UIView
。A swift'ified version of ivanzoid's answer
Swift 3
Swift 2
based around the underlying
CALayer
but easily translatable back toUIView
.Swift 4 & 4.2。 使用 XCode 10、iOS 12、模拟器和模拟器进行测试 运行 iOS 12.1 的 iPhone 6+。
这段代码工作正常。
Swift 4 & 4.2. Tested with XCode 10, iOS 12, Simulator & iPhone 6+ Running iOS 12.1.
This code work fine.
这是非常可怕和缓慢的。 基本上,您使用分配的后备存储创建一个位图上下文,以便可以读取内存,然后在上下文中渲染视图层并读取 RAM 中的适当点。
如果您已经知道如何对图像执行此操作,则可以执行以下操作:
然后您将获得一个可以获取像素数据的图像。 我确信您处理图像的机制涉及将它们渲染到上下文中,因此您可以将其与此合并并分解出实际的图像创建。 因此,如果您采取这一点并删除加载图像的部分并将其替换为上下文渲染:
您应该会很好。
It is pretty horrible and slow. Basically you create a bitmap context with a backing store you allocate so you can read the memory, then you render the views layer in the context and read the appropriate point in ram.
If you know how to do it for an image already you can do something like this:
And then you will get an image where you can get the pixel data. I am sure the mechanism you have for dealing with images involves rendering them into a context anyway, so you can merge that with this and factor out the actual image creation. So if you take that could and remove the bit where you load the image and replace it with the context render:
you should be good.
修复了一些小错误
此外,添加
到您的文件以避免警告消息。
将您的代码与此处找到的代码结合起来可以完美地工作。
Fixed some minor errors
Also, add
to your file to avoid warning messages.
Combining your code with the code found here works flawlessly.