我尝试使用writepixels()方法更改writablebitmap,但它不会更改任何像素。 它有以下的consructor
public void createWbm(int viewportW, int viewportH)
{
writeableBitmap = new WriteableBitmap(
viewportW,
viewportH,
96,
96,
PixelFormats.Indexed8,
new BitmapPalette(Form1.form1.getColors()));
i.Source = writeableBitmap;
}
我使用此方法调用leftbuttondown事件,但没有任何更改。是否有必要使用两个循环(外部为像素行,内部为列)来绘制每个像素,或者只使用writepixels()方法?感谢
void BrushPixel(MouseEventArgs e)
{
byte[] ColorData = { 0, 0, 0, 0 }; // B G R
Int32Rect rect = new Int32Rect(
(int)(e.GetPosition(i).X),
(int)(e.GetPosition(i).Y),
1,
1);
writeableBitmap.WritePixels( rect, ColorData, 4, 0);
}
答案 0 :(得分:0)
您使用不当,
ColorData
或者代表1x4,4x1或2x2像素的图像。rect
维度应与这些尺寸相匹配请注意,这些是调色板中颜色的索引,而不是您评论过的BGR值。
这是一个简单的例子:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var bitmap = new WriteableBitmap(100, 100, 96, 96, PixelFormats.Indexed8, BitmapPalettes.Halftone256);
int width = 50;
int height = 50;
var pixels = new byte[width*height];
var random = new Random();
random.NextBytes(pixels);
bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width, 0);
Image1.Source = bitmap;
}
}
XAML:
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="525"
Height="350"
SnapsToDevicePixels="True"
UseLayoutRounding="True">
<Grid>
<Border HorizontalAlignment="Center"
VerticalAlignment="Center"
BorderBrush="Black"
BorderThickness="1">
<Image x:Name="Image1" Stretch="None" />
</Border>
</Grid>
</Window>
注意:此格式stride
参数始终等于width
,因为像素长度(以字节为单位)为1.
我强烈建议您使用WriteableBitmapEx,这样可以让WriteableBitmap
操作变得更轻松。请注意它只支持PixelFormats.Pbgra32
,但除非你确实有一个特定的理由使用8位我只能推荐它,它可以绘制许多基元,如线条,矩形,圆形等......