我有一個圖像裁剪問題。當我嘗試使用矩形裁剪圖像時,裁剪區域被設置爲一些奇怪的值。 這裏是XAML代碼:WPF圖像裁剪
<Grid Name="GridImage">
<Image Name="LoadedImage" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality">
</Image>
<Canvas x:Name="ImageCanvas" ClipToBounds="True">
<Rectangle x:Name="SelectionRectangle" Stroke="LightBlue" Fill="#220000FF" Visibility="Collapsed" />
</Canvas>
</Grid>
這裏我剪切圖像如何:
var imagePosition = LoadedImage.TransformToAncestor(GridImage).Transform(new Point(0, 0));
Rect rect1 = new Rect(Math.Max(Canvas.GetLeft(SelectionRectangle) - imagePosition.X, 0), Math.Max(Canvas.GetTop(SelectionRectangle) - imagePosition.Y, 0), SelectionRectangle.Width, SelectionRectangle.Height);
var ratioX = LoadedImage.Source.Width/LoadedImage.ActualWidth;
var ratioY = LoadedImage.Source.Height/LoadedImage.ActualHeight;
Int32Rect rcFrom = new Int32Rect
{
X = (int)(rect1.X * ratioX),
Y = (int)(rect1.Y * ratioY),
Width = (int)(rect1.Width * ratioX),
Height = (int)(rect1.Height * ratioY)
};
try
{
BitmapSource bs = new CroppedBitmap((BitmapSource)LoadedImage.Source, rcFrom);
LoadedImage.Source = bs;
SetImageStretch(LoadedImage);
SetElementVisibility(Visibility.Hidden, Visibility.Visible, SelectionRectangle);
}
private void SetImageStretch(Image image)
{
if (image.Source.Width > image.ActualWidth || image.Source.Height > image.ActualHeight)
image.Stretch = Stretch.Uniform;
else image.Stretch = Stretch.None;
}
有誰知道如何解決這個問題?
Here how it looks before cropping
沒有一個很好的[mcve]可以可靠地再現你的問題,所以你不可能知道你需要什麼答案。最有可能的是,你根本不應該創建一個新的位圖,而是應該依靠「Image」元素的變換選項來簡單地約束原始位圖在屏幕上的顯示方式。請提供一個好的MCVE,並解釋_precisely_該代碼現在做了什麼以及您希望它做什麼。 –