我有Bitmap包装器的代码。 我需要创建一个重载构造函数,它从源图像中剪切一些矩形并将其放在_wbmp中。
Smth类似于公共Bitmap(字符串fileName,Rectangle区域)。 请分享一些解决方案。
public Bitmap(string fileName)
{
Uri uri = new Uri(fileName, UriKind.RelativeOrAbsolute);
StreamResourceInfo sri = null;
sri = Application.GetResourceStream(uri);
// Create a new WriteableBitmap object and set it to the JPEG stream.
BitmapImage bitmap = new BitmapImage();
bitmap.CreateOptions = BitmapCreateOptions.None;
bitmap.SetSource(sri.Stream);
_wbmp = new WriteableBitmap(bitmap);
}
谢谢
答案 0 :(得分:1)
WritableBitmap对象有一个Render方法,可以在添加一些转换后用于渲染新的位图。在您的情况下,您可以使用正确的新大小创建新的WritableBitmap以设置按钮右角,然后使用源添加临时图像并将其转换为左侧以设置左上角。像这样:
public static WriteableBitmap CropBitmap(string fileName, int newTop, int newRight, int newBottom, int newLeft)
{
Uri uri = new Uri(fileName, UriKind.RelativeOrAbsolute);
StreamResourceInfo sri = null;
sri = Application.GetResourceStream(uri);
// Create a new WriteableBitmap object and set it to the JPEG stream.
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.CreateOptions = BitmapCreateOptions.None;
bitmapImage.SetSource(sri.Stream);
//calculate bounding box
int originalWidth = bitmapImage.PixelWidth;
int originalHeight = bitmapImage.PixelHeight;
int newSmallWidth = newRight - newLeft;
int newSmallHeight = newBottom - newTop;
//generate temporary control to render image
Image temporaryImage = new Image { Source = bitmapImage, Width = originalWidth, Height = originalHeight };
//create writeablebitmap
WriteableBitmap wb = new WriteableBitmap(newSmallWidth, newSmallHeight);
wb.Render(temporaryImage, new TranslateTransform { X = -newLeft, Y = -newTop });
wb.Invalidate();
return wb;
}