Frage

Was ist die schnellsten (paar Zeilen Code und geringen Ressourcenverbrauch) ist Art und Weise einen leeren (0x0 Pixel oder 1x1 Pixel und vollständig transparent) Bitmap Beispiel in c #, die verwendet wird, wenn nichts gemacht werden soll.

War es hilfreich?

Lösung

Mit dem Methode erstellen.

Beispiel von MSDN gestohlen:)

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

Andere Tipps

Dank Arcutus Hinweis ich das jetzt haben ( Weiche funktioniert gut):

var i = BitmapImage.Create(
    2,
    2,
    96,
    96,
    PixelFormats.Indexed1,
    new BitmapPalette(new List<Color> { Colors.Transparent }),
    new byte[] { 0, 0, 0, 0 },
    1);

Wenn ich das Bild kleiner machen bekomme ich ein Argument. Ich habe keine Ahnung, warum kann ich nicht ein kleineres Bild, dass 2x2px erstellen.

Die Art und Weise ein solches Bild zu erzeugen, ohne ein großes Managed Byte-Array Zuweisung ist TransformedBitmap zu verwenden.

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

Die minimalste Bitmap kann wie folgt erzeugt werden:

    public static BitmapSource CreateEmptyBitmap()
    {
        return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] {0}, 1);
    }

Werfen Sie einen Blick auf diese. Es funktioniert für jedes 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;
    }

Eine andere Möglichkeit ist eine Instanz einer Klasse Bitmap zu schaffen, die von Bitmap abgeleitet:

BitmapSource emptySource = new BitmapImage();

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top