Skip to content

Instantly share code, notes, and snippets.

@BrunoVT1992
Created July 20, 2017 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrunoVT1992/b226d500de578b47cc23f2e7f52f4fa2 to your computer and use it in GitHub Desktop.
Save BrunoVT1992/b226d500de578b47cc23f2e7f52f4fa2 to your computer and use it in GitHub Desktop.
UIImage extension to get a pixel color for Xamarin iOS
using System.Drawing;
using System.Runtime.InteropServices;
using CoreGraphics;
using UIKit;
namespace iOS
{
public static class UIImageExtensions
{
public static string GetPixelHexColor(this UIImage image, float x, float y)
{
string hexCode = null;
var point = new PointF(x, y);
var rawData = new byte[4];
var handle = GCHandle.Alloc(rawData);
try
{
using (var colorSpace = CGColorSpace.CreateGenericRgb())
{
using (var context = new CGBitmapContext(rawData, 1, 1, 8, 4, colorSpace, CGImageAlphaInfo.PremultipliedLast))
{
context.DrawImage(new RectangleF(-point.X, point.Y - (float)image.Size.Height, (float)image.Size.Width, (float)image.Size.Height), image.CGImage);
hexCode = string.Format("#{0}{1}{2}{3}", rawData[3].ToString("X2"), rawData[0].ToString("X2"), rawData[1].ToString("X2"), rawData[2].ToString("X2"));
}
}
}
finally
{
handle.Free();
}
return hexCode;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment