CroppedBitmapは画像の周りにスペースを追加することをサポートしていないように思われるので、透明な画像をWriteableBitmapを使って正しいサイズで作成することができます。入力がターゲットサイズより小さい場合、このメソッドはそれを拡大しますが、変更するのは簡単です。
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;
}
あなたはすでにあなたがスケーリングを行うためにViewBoxをして、それをラップでしたが、あなただけの通常の画像で作業している場合、私は上記の方法を使用したいRenderTargetBitmap使用してコンテンツをレンダリングしている場合。
@Krisこれは非常に有望ですね。私はこれらのメソッドに新しいです。 BitmapSourceとBitmapFrameの違いを教えてください。 BitmapFrameを使用して画像のサイズを変更しています。 – mrtsherman
@Kris大丈夫です。BitmapFrameはBitmapSourceの子です。だから、コードを動作させることができるはずです。今自分を試している。 – mrtsherman
BitmapFrameの主な用途は、gifのようないくつかの画像フォーマットは複数のフレームを持つことができるため、デコーダに結びつけてサムネイルを提供するためです。詳細については、http://stackoverflow.com/questions/155391/difference-between- a-bitmapframe-and-bitmapimage-in-wpf – Kris