Domanda

Qual è più rapida (poche linee di codice e l'utilizzo delle risorse basso) modo per creare un vuoto (0x0 px o 1x1 px e completamente trasparente) BitmapSource esempio in C # che viene utilizzato quando nulla dovrebbe essere reso.

È stato utile?

Soluzione

Utilizza la Crea metodo.

Esempio rubato da 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);

Altri suggerimenti

Grazie a Arcutus suggerimento ho questo ora ( Quale funziona bene):

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

Se faccio questa immagine più piccola ottengo un ArgumentException. Non ho idea perché non riesco a creare un'immagine più piccola che 2x2px.

Il modo per creare una tale immagine senza allocare una grande matrice di byte gestito è utilizzare 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));

Il BitmapSource più minimale può essere generato in questo modo:

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

Basta dare un'occhiata a questo. Funziona per qualsiasi 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;
    }

Un altro modo è quello di creare un'istanza di una classe BitmapImage che è derivata da BitmapSource:

BitmapSource emptySource = new BitmapImage();

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top