سؤال

ما هي أسرع (أسطر قليلة من التعليمات البرمجية واستخدام الموارد المنخفضة) لإنشاء فارغة (0x0 px أو 1x1 px وشفافة تمامًا) نقطية مثيل في 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 لدي هذا الآن (Wich يعمل بشكل جيد):

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

إذا جعلت هذه الصورة أصغر ، أحصل على enbumentException. ليس لدي أدنى فكرة لماذا لا يمكنني إنشاء صورة أصغر 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);
    }

مجرد إلقاء نظرة على هذا. إنه يعمل مع أي بيكسلورمات

  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:

BitmapSource emptySource = new BitmapImage();

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top