简体   繁体   English

检测UIImage是浅色还是深色

[英]Detect if UIImage is light or dark

I need some help to create a smart detector that can detect if a UIImage is light or dark, so that I can but on a UILabel with a textColor in the opposite color, either black or white. 我需要一些帮助来创建一个智能检测器,该检测器可以检测UIImage是亮还是暗,以便我可以在UILabel上使用textColor为相反颜色的黑色或白色。

Can this be done in a few lines or do I need a hardcore CoreImage manoeuvre? 可以在几行中完成吗,还是我需要一个核心的CoreImage操作?

Thanks! 谢谢!

Seeing if the image is "dark" or "light" won't work generally. 通常看不到图像是“暗”还是“亮”。 The part you end up putting the text on could have both light and dark parts even if the overall image might be considered one or the other. 即使将整体图像视为一个或另一个,您最终放置文本的部分也可能同时具有亮和暗部分。

A common solution to adding text to a random picture is to add a partially transparent black background to the white text (or a partially transparent white background to black text). 向随机图片添加文本的常见解决方案是向白色文本添加部分透明的黑色背景(或向黑色文本添加部分透明的白色背景)。

If you have a random image, you will have to inspect all the pixels. 如果图像随机,则必须检查所有像素。 You can't just inspect some pixels - as a counterexample, you can imagine an image that is entirely white with only some black pixels and you inspect only them. 您不能只检查一些像素-作为反例,您可以想象只有一个黑色像素的全白色图像,而您仅检查它们。 That would give you bad results. 那会给你不好的结果。

The simplest solution I can imagine would be to convert the image to grayscale and then go through all the pixels, calculating the average gray. 我能想到的最简单的解决方案是将图像转换为灰度,然后遍历所有像素,计算出平均灰度。 Then you can decide if the average is closer to white or closer to black. 然后,您可以确定平均值是接近白色还是接近黑色。

You can also downscale the image before processing (drawing the image into a smaller image). 您还可以在处理之前缩小图像的比例(将图像绘制成较小的图像)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM