c# – 在Java SWT中使用ImageData在Canvas上显示图像的WPF等价物是什么

前端之家收集整理的这篇文章主要介绍了c# – 在Java SWT中使用ImageData在Canvas上显示图像的WPF等价物是什么前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
什么是以下 @L_403_0@ SWT代码的WPF等价物?我想从RGBA值列表中创建一个Image并在Canvas上显示.
private Image GetImage()
{

    ImageData imageData = new ImageData(imageWidth,imageHeight,32,palette);

    int pixelVecLoc=0;
    for (int h = 0; h<imageHeight && (pixelVecLoc < currentImagePixelVec.size()); h++)
    {
        for (int w = 0; w<imageWidth && (pixelVecLoc < currentImagePixelVec.size()); w++)
        {
            int p = 0;
            Pixel pixel = currentImagePixelVec.get(pixelVecLoc);
            p = (pixel.Alpha<<24) | (pixel.Red<<16) | (pixel.Green<<8) | pixel.Blue;                
            imageData.setPixel(w,h,p);            
            pixelVecLoc++;
        }
    }

    imageData = imageData.scaledTo(imageScaleWidth,imageScaleHeight);
    Image image = ImageDescriptor.createFromImageData(imageData).createImage();
    return image;   
}

然后在Canvas上绘制它:

gc.drawImage(image,0);

解决方法

这是一个简短的片段,展示了如何创建自定义RGBA缓冲区并向其写入像素数据( based on this example):
int width = 512;
int height = 256;
int stride = width * 4 + (width % 4);
int pixelWidth = 4;  // RGBA (BGRA)
byte[] imageData = new byte[width * stride];       // raw byte buffer

for (int y = 0; y < height; y++)
{
    int yPos = y * stride;

    for (int x = 0; x < width; x++)
    {
        int xPos = yPos + x * pixelWidth;

        imageData[xPos + 2] = (byte) (RedValue);   // replace *Value with source data
        imageData[xPos + 1] = (byte) (GreenValue);
        imageData[xPos    ] = (byte) (BlueValue);
        imageData[xPos + 3] = (byte) (AlphaValue);
    }
}

然后将BitmapSource.Create Method (Int32, Int32, Double, PixelFormat, BitmapPalette, IntPtr, Int32)方法PixelFormats一起使用:

BitmapSource bmp = 
  BitmapSource.Create(
    width,height,96,// Horizontal DPI
    96,// Vertical DPI
    PixelFormats.Bgra32,// 32-bit BGRA
    null,// no palette
    imageData,// byte buffer
    imageData.Length,// buffer size
    stride);               // stride

请注意,除了代码段中所示的alpha分量(BGRA)之外,字节顺序是反向的.

要将结果传输到画布,您可以先创建一个Image,将BitmapSource设置为Source,最后将其添加到画布:

// create image and set image as source
Image BmpImg = New Image();
BmpImg.Width = width;
BmpImg.Height = height;
BmpImg.Source = bmp;

// add image to canvas
canvas.Children.Add(BmpImg);

Canvas.SetLeft(BmpImg,0);  // to set position (x,y)
Canvas.SetTop(BmpImg,0);
原文链接:/csharp/100813.html

猜你在找的C#相关文章