Created
July 20, 2017 13:05
-
-
Save BrunoVT1992/b226d500de578b47cc23f2e7f52f4fa2 to your computer and use it in GitHub Desktop.
UIImage extension to get a pixel color for Xamarin iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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