The Blog

Color of raw image pixel data and iPhone 4’s retina display

In my Ambient Mood Lamp app, I have a color picker where you can choose the background color by simply tapping the color on an image, like this:

Color swirl

What I need from there is the actual RGB representation of the pixel color. To get that, there’s quite a bit of code involved. A large part of it is taken from Apple’s technical note QA1509.

Pixel color fetching is done in this if block from that article:

OBJC:
  1. if (data != NULL)
  2. {
  3. // **** You have a pointer to the image data ****
  4. // **** Do stuff with the data here ****
  5. }

I picked up the code to get the pixel color from some web page I lost track of. This is the code:

OBJC:
  1. int offset = ((w*round(point.y))+round(point.x)) * 4;
  2. int alpha = data[offset];
  3. int red = data[offset+1];
  4. int green = data[offset+2];
  5. int blue = data[offset+3];
  6. color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];

w is the width of one row of data, and point {x,y} is where the screen was touched. The * 4 in the first line means 4 bytes of raw data per pixel. Well, 4 bytes when your screen res is up to 160ish ppi. On iPhone 4’s Retina Display, with its 326ppi resolution, this should be 8. Which means correct code now is:

OBJC:
  1. int offset = ((w*round(point.y))+round(point.x)) * 4 * [[UIScreen mainScreen] scale];

Welcome to wonderful world of resolution independent programming.

Banca

Banca

Beautiful and functional currency converter, supports just about any currency in the world.

Go Couch to 5k

Go Couch to 5k

The most popular starter running program in beautiful feature-rich app (GPS tracking, charts, detailed history etc)

Quickie to do

Quickie to do

The fastest short-term task-list / check-list app on the App Store. Really.

Guerrilla Cardio

Guerrilla Cardio

The most challenging high-impulse interval training in the world.

Run Mate

Run Mate

A versatile running coach app, with unlimited number of running programs. Perfect for casual runners.

Comments are closed.