0

我有这样的位图包装代码。我需要创建重载构造函数,它从源图像中剪切一些矩形并将其放入_wbmp。

类似于 public Bitmap(string fileName, Rectangle area)。请分享一些解决方案。

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);
    }

谢谢

4

1 回答 1

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;
    }
于 2013-06-10T14:56:18.140 回答