我有一个 UILabel
放在 UIImageView
之上。 UIImageView
可以改变显示各种图像。根据 UIImageView
中显示的图像,UILabel
的文本颜色必须能够动态更改。例如,当显示浅色图像时,将使用深色 UILabel
文本颜色,或者当使用深色图像时,将使用浅色文本。
在 Swift 中,什么是最好、最简单、最有效的方法来提取单个像素的 RGB 值或一组像素的平均 RGB 值,直接位于 UILabel
的位置后面在 UIImage
之上?
或者更妙的是,在 Swift 中,是否有一个 UILabel
方法可以根据位于上方的背景动态更改文本颜色?
谢谢。
最佳答案
老实说,我什至不会抓取 RGB,你应该知道你将什么图像放入 UIImageView,所以根据它来规划标签。
如果你必须选择 RGB,那么就这样做,像这样:
UIGraphicsBeginImageContext(CGSizeMake(1,1));
let context = UIGraphicsGetCurrentContext()
//We translate in the opposite direction so that when we draw to the canvas, it will draw our point at the first spot in readable memory
CGContextTranslateCTM(context, -x, -y);
// Make the CALayer to draw in our "canvas".
self.layer.renderInContext(context!);
let colorpoint = UnsafeMutablePointer<UInt32>(CGBitmapContextGetData(context));
UIGraphicsEndImageContext();
其中 x 和 y 是您要抓取的点,self 是您的 UIImageView。
编辑:@Mr.T 也发布了如何完成此操作的链接,如果您需要平均值,只需通过更改 UIGraphicsBeginImageContext(CGSizeMake(1,1)); 获取所需的像素数量;
到 UIGraphicsBeginImageContext(CGSizeMake(width,height));
并用该数据计算平均值
关于xcode - 在 Swift 中的 UILabel 后面的 UIImageView 中获取像素的 RGB 值或像素的平均 RGB 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33710171/