如何在 UIView 中获取像素的颜色? [英] How to get the color of a pixel in an UIView?

查看:33
本文介绍了如何在 UIView 中获取像素的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个小型应用程序.在其中,我需要检测 UIView 中像素的颜色.我有一个 CGPoint 定义了我需要的像素.使用 CoreAnimation 更改 UIView 的颜色.

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.

我知道有一些复杂的方法可以从 UIImages 中提取颜色信息.但是我找不到 UIViews 的解决方案.

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];

非常感谢任何输入.

推荐答案

这非常可怕且缓慢.基本上,您使用分配的后备存储创建位图上下文,以便您可以读取内存,然后在上下文中渲染视图层并读取 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:

- (UIImage *)imageForView:(UIView *)view {
  UIGraphicsBeginImageContext(view.frame.size);
  [view.layer renderInContext: UIGraphicsGetCurrentContext()];
  UIImage *retval = UIGraphicsGetImageFromCurrentImageContext(void);
  UIGraphicsEndImageContext();

  return retval;
}

然后您将获得一个图像,您可以在其中获取像素数据.我确信您处理图像的机制无论如何都涉及将它们渲染到上下文中,因此您可以将其与此合并并排除实际的图像创建.因此,如果您可以删除加载图像的位并将其替换为上下文渲染:

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:

[view.layer renderInContext: UIGraphicsGetCurrentContext()];

你应该很好.

这篇关于如何在 UIView 中获取像素的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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