1

I have a UILabel that is placed on top of a UIImageView. The UIImageView can change displaying a variety of images. Depending on the image displayed in the UIImageView, the UILabel's text color must be able to change dynamically. For instance, when a light colored image is displayed, a dark UILabel text color will be used, or when a dark image is used, a light text color will be used.

In Swift, what is the best, simple, most efficient method to extract the RGB value of a single pixel or average RGB value of a group of pixels directly behind the position of UILabel that is sitting above a UIImage?

Or even better, in Swift, is there a UILabel method that changes the text colour dynamically based on the background it is positioned above?

Thank you.

enter image description here

user4806509
  • 2,925
  • 5
  • 37
  • 72
  • you should be more clear!!! do u need average colour ? or top most colour ? or colour where touched ? – Teja Nandamuri Nov 14 '15 at 15:49
  • http://stackoverflow.com/questions/12770181/how-to-get-the-pixel-color-on-touch – Teja Nandamuri Nov 14 '15 at 15:49
  • Sorry if I wasn't clear @Mr.T An average color in the region of the UILabel is what is needed. (So, for example, if the UILabel is 50x10 pixels, the area needed for the average will also be 50x10 pixels in the exact same position from the UIImageView.) Thanks for that link, it refers to a single pixel though. I think an average would be much more robust. Any suggestion on a complete and simple Swift answer. – user4806509 Nov 14 '15 at 15:56

1 Answers1

0

Honestly, I would not even grab RGB, you should know what image you are putting into UIImageView, so plan the label based on that.

If you must choose RGB, then do so,thing like this:

    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();

Where x and y is the point you want to grab, and self is your UIImageView.

Edit: @Mr.T posted a link to how this is done as well, if you need the average, just grab the amount of pixels needed by changing UIGraphicsBeginImageContext(CGSizeMake(1,1)); to UIGraphicsBeginImageContext(CGSizeMake(width,height)); and compute the average with that data

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44