SkiaSharp与MAUI坐标系统理解及绘图异常问题求助
SkiaSharp矩形坐标与图像提取异常问题
已知SkiaSharp矩形原点位于左上角,但实际使用中出现理解偏差,尝试官方教程后仍未解决。
问题场景
- 目标Bitmap尺寸为1080×1080:直接创建
SKRect(0,0,1080,1080)作为目标区域时,画布绘图空白;但通过Maui.Rect(0,0,1080,1080)转换为SKRect却能正常工作。 - 调整源区域坐标测试:
- 目标区域设为
SKRect(100,100,980,980)(避免超出Bitmap范围),仍空白; - 源区域设为
SKRect(100,100,150,150)(确认在源Bitmap范围内),同样空白。
- 目标区域设为
补充:有评论提到坐标基于Image控件,但当前仅上传图片未显示,无法获取该控件。项目目标是掌握通过设置源矩形坐标提取图像任意指定区域的方法。
示例代码对比
正常显示的代码
SKBitmap destination = new SKBitmap(1080, 1080); Rect destRec = new Rect(0,0,1080,1080); SKRect dest = SkiaSharp.Views.Maui.Extensions.ToSKRect(destRec); var height = sourceMap.Height; var width = sourceMap.Width; SKRect source = new SKRect(0,0,width,height);
异常的代码(源矩形宽高各加100,源图宽2000、高1332)
SKBitmap destination = new SKBitmap(1080, 1080); Rect destRec = new Rect(0,0,1080,1080); SKRect dest = SkiaSharp.Views.Maui.Extensions.ToSKRect(destRec); var height = sourceMap.Height; var width = sourceMap.Width; SKRect source = new SKRect(0,0,width+100,height+100);
附完整代码
View代码(XAML)
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" xmlns:ImageCroppingTry2="clr-namespace:ImageCroppingTry2" x:DataType="ImageCroppingTry2:MainPageViewModel" x:Class="ImageCroppingTry2.MainPage"> <ContentPage.Resources> <ResourceDictionary> <toolkit:ByteArrayToImageSourceConverter x:Key="ByteArrayToImageSourceConverter" /> </ResourceDictionary> </ContentPage.Resources> <VerticalStackLayout> <Image x:Name="displayImage" Source="{Binding Image, Converter={StaticResource ByteArrayToImageSourceConverter}}"/> <Button Command="{Binding UploadImageCommand}"></Button> </VerticalStackLayout>
ViewModel代码
[ObservableProperty] public byte[] image; [RelayCommand] public async void UploadImage() { // 选择照片 FileResult im = await MediaPicker.Default.PickPhotoAsync(); SKBitmap sourceMap; using (Stream s = await im.OpenReadAsync()) { using (MemoryStream ms = new MemoryStream()) { await s.CopyToAsync(ms); ms.Seek(0, SeekOrigin.Begin); sourceMap = SKBitmap.Decode(ms); } } SKBitmap destination = new SKBitmap(1080, 1080); Rect destRec = new Rect(0,0,1080,1080); //SKRect dest = new SKRect(0,0 , 1080,1080); SKRect dest = SkiaSharp.Views.Maui.Extensions.ToSKRect(destRec); //Rect sourceRect = new Rect(0,0,destination.Width,destination.Height); SKRect source = new SKRect(0,0,150,150); //SKRect source = SkiaSharp.Views.Maui.Extensions.ToSKRect(sourceRect); using (SKCanvas canvas = new SKCanvas(destination)) { canvas.Clear(); canvas.DrawBitmap(sourceMap, source, dest); } SKImage skImage = SKImage.FromBitmap(destination); SKData encoded = skImage.Encode(); using (MemoryStream memory = new MemoryStream()) { encoded.AsStream().CopyTo(memory); Image = memory.ToArray(); } }
内容的提问来源于stack exchange,提问作者WoistdasNiveau
相关产品推荐
相关产品推荐

