質問
空の(0x0 pxまたは1x1 px、完全に透明)を作成するための最速(コードの数行と低いリソース使用量)の方法は何ですか? BitMapsource c#のインスタンスは、何もレンダリングされないときに使用されます。
解決
使用 作成 方法。
MSDNから盗まれた例::)
int width = 128;
int height = width;
int stride = width/8;
byte[] pixels = new byte[height*stride];
// Try creating a new image with a custom palette.
List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
colors.Add(System.Windows.Media.Colors.Red);
colors.Add(System.Windows.Media.Colors.Blue);
colors.Add(System.Windows.Media.Colors.Green);
BitmapPalette myPalette = new BitmapPalette(colors);
// Creates a new empty image with the pre-defined palette
BitmapSource image = BitmapSource.Create(
width, height,
96, 96,
PixelFormats.Indexed1,
myPalette,
pixels,
stride);
他のヒント
ありがとう Arcutusのヒント 私は今これを持っています(うまくいきます):
var i = BitmapImage.Create(
2,
2,
96,
96,
PixelFormats.Indexed1,
new BitmapPalette(new List<Color> { Colors.Transparent }),
new byte[] { 0, 0, 0, 0 },
1);
この画像を小さくすると、ArgumentExceptionが表示されます。 2x2pxの小さな画像を作成できない理由はわかりません。
大きな管理されたバイト配列を割り当てることなくそのような画像を作成する方法は、使用することです TransformedBitmap
.
var bmptmp = BitmapSource.Create(1,1,96,96,PixelFormats.Bgr24,null,new byte[3]{0,0,0},3);
var imgcreated = new TransformedBitmap(bmptmp, new ScaleTransform(width, height));
最も最小限のビットマプシュースは、次のように生成できます。
public static BitmapSource CreateEmptyBitmap()
{
return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] {0}, 1);
}
これを見てください。任意のpixelformatで機能します
public static BitmapSource CreateEmtpyBitmapSource(int width, int height, PixelFormat pixelFormat)
{
PixelFormat pf = pixelFormat;
int rawStride = (width * pf.BitsPerPixel + 7) / 8;
var rawImage = new byte[rawStride * height];
var bitmap = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, rawStride);
return bitmap;
}
別の方法は、BitMapsourceから派生したBitMapImageクラスのインスタンスを作成することです。
BitmapSource emptySource = new BitmapImage();
所属していません StackOverflow