xcode - 在 Swift 中的 UILabel 后面的 UIImageView 中获取像素的 RGB 值或像素的平均 RGB 值

标签 xcode swift optimization uiimageview uilabel

我有一个 UILabel 放在 UIImageView 之上。 UIImageView 可以改变显示各种图像。根据 UIImageView 中显示的图像,UILabel 的文本颜色必须能够动态更改。例如,当显示浅色图像时,将使用深色 UILabel 文本颜色,或者当使用深色图像时,将使用浅色文本。

在 Swift 中,什么是最好、最简单、最有效的方法来提取单个像素的 RGB 值或一组像素的平均 RGB 值,直接位于 UILabel 的位置后面在 UIImage 之上?

或者更妙的是,在 Swift 中,是否有一个 UILabel 方法可以根据位于上方的背景动态更改文本颜色?

谢谢。

enter image description here

最佳答案

老实说,我什至不会抓取 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/

相关文章:

c++ - 编译器何时内联 C++ 代码?

c++ - 为什么 clang 不像 #define 那样优化全局常量?

xcode - Xcode不检测预操作是否失败是正常的吗?

ios - 如何在 UIVIew 的底部添加阴影

ios - 快速键盘向上移动两次

swift - "Order"使用 Swift 关闭 Mac

macOS 上的 SwiftUI,如何在 Button 上使用自定义图像符号?

xcode - Xcode 6在提交存档时崩溃

ios - 将推送通知添加到我的应用程序

node.js - 在 Node.js 中操作从数据库中获取的数字的最佳/最合适的方法