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