Method: UIImage#color_at

Defined in:
lib/sugarcube-image/uiimage.rb

#color_at(point) ⇒ Object

Oddly enough, this method doesn't seem to have retina support



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/sugarcube-image/uiimage.rb', line 448

def color_at(point)
  point = SugarCube::CoreGraphics::Point(point)
  point.x *= self.scale
  point.y *= self.scale

  # First get the image into your data buffer
  cgimage = self.CGImage
  width = CGImageGetWidth(cgimage)
  height = CGImageGetHeight(cgimage)
  bytes_per_pixel = 4
  bits_per_component = 8
  bytes_per_row = bytes_per_pixel * width
  @raw_data || begin
    color_space = CGColorSpaceCreateDeviceRGB()
    @raw_data = Pointer.new(:uchar, height * width * 4)
    context = CGBitmapContextCreate(@raw_data, width, height, bits_per_component, bytes_per_row, color_space, KCGImageAlphaPremultipliedLast | KCGBitmapByteOrder32Big)

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgimage)
  end

  # Now @raw_data contains the image data in the RGBA8888 pixel format.
  xx = point.x.round
  yy = point.y.round
  byte_index = (bytes_per_row * yy) + xx * bytes_per_pixel
  red = @raw_data[byte_index]
  green = @raw_data[byte_index + 1]
  blue = @raw_data[byte_index + 2]
  alpha = @raw_data[byte_index + 3]
  return [red, green, blue].uicolor(alpha / 255.0)
end