扩展画布/透明背景的BitmapImage在一个WPF应用程序画布、应用程序、透明、背景

由网友(lack of love (缺爱))分享简介:这是Save图像文件保持纵横比在一个WPF应用程序 我知道HOWTO规模的形象,但我怎么扩大画布大小,保证图像还是有要求的宽度和高度。在这个例子中的250X250,但是它的动态。I know howto scale the image, but how do I expand the canvas size, to...

这是Save图像文件保持纵横比在一个WPF应用程序

我知道HOWTO规模的形象,但我怎么扩大画布大小,保证图像还是有要求的宽度和高度。在这个例子中的250X250,但是它的动态。

I know howto scale the image, but how do I expand the canvas size, to ensure the image still has the requested width and height. In this example its 250x250 but its dynamic.

我创建了这个例子来展示一下我试图帮凶。

I have created this illustration to show what I'm trying to accomplice.

我找不到任何方式扩大了的BitmapImage的画布,也没有办法在正确的尺寸创建一个在内存中的图像,具有透明背景,然后合并两个图像组合在一起。

I can't find any way of expanding the canvas of an BitmapImage, nor a way to create an in memory image in the correct size, with a transparent background, and then merging the two images together.

推荐答案

CroppedBitmap似乎不支持添加图像周围的空间,因此,你可以创建一个透明图像使用正确尺寸的 WriteableBitmap的。如果输入是比目标尺寸小此方法将其放大,但是,很容易改变。

CroppedBitmap doesn't seem to support adding space around an image so instead you can create a transparent image the correct size using WriteableBitmap. If the input is smaller than the target size this method will enlarge it, but that is easy to alter.

public static BitmapSource FitImage(BitmapSource input, int width, int height)
{
    if (input.PixelWidth == width && input.PixelHeight == height)
        return input;

    if(input.Format != PixelFormats.Bgra32 || input.Format != PixelFormats.Pbgra32)
        input = new FormatConvertedBitmap(input, PixelFormats.Bgra32, null, 0);

    //Use the same scale for x and y to keep aspect ratio.
    double scale = Math.Min((double)width / input.PixelWidth, height / (double)input.PixelHeight);

    int x = (int)Math.Round((width - (input.PixelWidth * scale))/2);
    int y = (int)Math.Round((height - (input.PixelHeight * scale))/2);


    var scaled = new TransformedBitmap(input, new ScaleTransform(scale, scale));
    var stride = scaled.PixelWidth * (scaled.Format.BitsPerPixel / 8);

    var result = new WriteableBitmap(width, height, input.DpiX, input.DpiY, input.Format,null);

    var data = new byte[scaled.PixelHeight * stride];
    scaled.CopyPixels(data, stride, 0);
    result.WritePixels(new Int32Rect(0,0,scaled.PixelWidth,scaled.PixelHeight), data, stride,x,y);
    return result;
}

如果您使用的是RenderTargetBitmap已经呈现的内容,你可以把它包在一个视框做缩放,但如果你只是工作与正常的图像我会用上面的方法。

If you are already rendering content using RenderTargetBitmap you could wrap it in a ViewBox to do the scaling but if you're just working with normal images I'd use the above method.

阅读全文

相关推荐

最新文章