如何获取UIView中像素的颜色

如何获取UIView中像素的颜色

本文介绍了如何获取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中像素的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 22:29