Hello,
Firstly, Image do not have method to get the Pixel in the MAUI.
But you can do it by SkiaSharp.
Before you start it, please install SkiaSharp.Views.Maui.Controls 2.88.9
.
Then, we need to get the Image by Stream. So, I copy the image(make sure the build action to MauiAssets) to the Raw folder for testing.
Here is my Image XAML layout. I add tap GestureRecognizer to make a test.
<Image
Source="dotnet_bot.png"
Background="Gray"
HeightRequest="185"
Aspect="AspectFit"
SemanticProperties.Description="dot net bot in a race car number eight" >
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
</Image.GestureRecognizers>
</Image>
Here is TapGestureRecognizer_Tapped, I load the image from the assets folder, if I click the image, I get the position and need to convert clicked position to bitmap's position by RadioX and RadioY.
In the end, we can get the pixel color by var pixelColor = bitmap.GetPixel(x, y);
.
private async void TapGestureRecognizer_Tapped(object sender, TappedEventArgs e)
{
Image image= sender as Image;
using var stream = await FileSystem.OpenAppPackageFileAsync("bot.png");
if (stream == null)
{
DisplayAlert("Error", "cannot load image sources", "OK");
return;
}
// use SkiaSharp to load the image
using var bitmap = SKBitmap.Decode(stream);
//get the Radio by bitmap and Image
double radioX = bitmap.Width / image.Width;
double radioY = bitmap.Height / image.Height;
var res = e.GetPosition(image);
// Convert current click pixel value to the bitmap value
int x =(int) (res.Value.X* radioX); // get X value
int y = (int)(res.Value.Y*radioY); // get Y value
if (x >= 0 && x < bitmap.Width && y >= 0 && y < bitmap.Height)
{
// get the pixel color
var pixelColor = bitmap.GetPixel(x, y);
// display color information
await DisplayAlert("pixel color", $"R={pixelColor.Red}, G={pixelColor.Green}, B={pixelColor.Blue}, A={pixelColor.Alpha}", "OK");
}
else
{
await DisplayAlert("Error", "Over the image's range", "OK");
}
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.