Question

Quel est le plus rapide (quelques lignes de code et une faible utilisation des ressources) façon de créer un vide (0x0 px ou 1x1 px et entièrement transparent) l'instance de BitmapSource en C # qui est utilisé quand doit être rendu rien.

Était-ce utile?

La solution

Utilisez le Créer méthode.

Exemple volée à 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);

Autres conseils

Merci à indice Arcutus Je cela maintenant ( Wich fonctionne très bien):

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

Si je fais cette petite image, je reçois un ArgumentException. Je n'ai aucune idée pourquoi je ne peux pas créer une image plus petite que 2x2px.

La façon de créer une telle image sans attribution d'un grand tableau d'octets géré est d'utiliser 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));

Le plus BitmapSource minimal peut être généré comme ceci:

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

Il suffit de jeter un oeil à ce sujet. Il fonctionne pour tout 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;
    }

Une autre façon est de créer une instance d'une classe BitmapImage qui est dérivé de BitmapSource:

BitmapSource emptySource = new BitmapImage();

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top