一个MainWindow,new Image()加入,通过 DispatchTimer,将图像每行(50pixel)下移,由黑到白。
同时移动控件移动。
你看这个算“闪烁”吗?
问chatGPT回答的。
public partial class MainWindow : Window
{
private WriteableBitmap bitmap;
private Image image;
private DispatcherTimer timer;
private int fromRow = 0;
private double imagePositionX = 0;
private double imageMovementSpeed = 5; // Adjust speed as needed
public MainWindow()
{
InitializeComponent();
int width = 9;
int height = 9;
int cellSize = 50;
bitmap = new WriteableBitmap(width * cellSize, height * cellSize, 96, 96, PixelFormats.Bgr32, null);
image = new Image();
image.Stretch = Stretch.None;
image.Source = bitmap;
this.Content = image;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(0.05); // 变快或变慢
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
int width = 9;
int height = 9;
int cellSize = 50;
bitmap.Lock();
for (int j = 0; j < height; j++)
{
int row = (j + fromRow) % height;
for (int i = 0; i < width; i++)
{
int value = i * width + j + 1;
int x = i * cellSize;
int y = (row + height) % height * cellSize;
byte[] pixels = new byte[cellSize * cellSize * 4];
for (int k = 0; k < cellSize; k++)
{
for (int l = 0; l < cellSize; l++)
{
int index = (k * cellSize + l) * 4;
pixels[index + 0] = (byte)(value * 255 / 9);
pixels[index + 1] = (byte)(value * 255 / 9);
pixels[index + 2] = (byte)(value * 255 / 9);
pixels[index + 3] = 255;
}
}
bitmap.WritePixels(new Int32Rect(x, y, cellSize, cellSize), pixels, cellSize * 4, 0);
}
}
fromRow++;
bitmap.AddDirtyRect(new Int32Rect(0, 0, width * cellSize, height * cellSize));
bitmap.Unlock();
// position
imagePositionX += imageMovementSpeed;
if (imagePositionX >= this.ActualWidth)
{
imagePositionX = -imagePositionX;
}
image.Margin = new Thickness(imagePositionX, 0, 0, 0); // Set margin instead of Canvas.SetLeft
}
}
【 在 capriccio 的大作中提到: 】
: 感谢大神
: 问题其实很简单,就是我用了一个Image对象显示图片,Image对象较大,窗口只显示其中一部分。其中一个步骤是先更新Image中的图像数据,然后移动Image的位置(调整Margin),
: 并保证这两个操作之后窗口中显示出来的图像是不变的,也就是从界面上看不到这个操作(也不希望看到)。一般情况是可以的,但有一定概率(大概1/5?)会闪一下,我猜测是更新图像数据后界面刷新了一下,然后才移动了Image的位置。
: ...................
--
修改:DoorWay FROM 124.114.151.*
FROM 124.114.151.*