C# - 使用Graphics.DrawImage的动画

时间:2014-01-22 09:41:59

标签: c# image

我在分辨率为1920 x 1080的计算机上制作动画图像。

当我在分辨率较低的计算机上运行相同的程序时,图像移动得非常快,当我使用更大的分辨率时,它的移动速度很慢:

我的代码:

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics kp = e.Graphics;
        kp.DrawImage(image, point.X, point.Y, width, height);
    }

    private void timer_move_Tick(object sender, EventArgs e)
    {
        point.X += 5;
        Refresh();
    }

我该如何解决?

编辑:

图像尺寸按屏幕分辨率计算。

编辑2:

我这里有更多照片,其中一张照片是每个timer_move_Tick更小。

代码:

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics kp = e.Graphics;
        kp.DrawImage(image, point.X, point.Y, width, height);
        kp.DrawImage(image2, point2.X, point2.Y, width2, height2);
    }

    private void timer_move_Tick(object sender, EventArgs e)
    {
        point.X += 5;
        width2 -= 1; /*This is the problem*/
        height2 -= Convert.ToInt32(percent_width / 9);
        point2.Y -= Convert.ToInt32(percent_width / 2);
        Refresh();
    }

2 个答案:

答案 0 :(得分:0)

timer_move_tick功能中,您添加到point.X的值必须是百分比(或相对于屏幕尺寸)的值。这样,无论你有什么分辨率,图像都会以相同的速度移动。

编辑后:如果计算的图像大小与屏幕分辨率有关,则增加的point.X值也必须与之相关。如果是,您将获得与图像相同的行为。

答案 1 :(得分:0)

您可以使用Screen.Bounds获取解析信息:

var screenResolution = Screen.PrimaryScreen.Bounds.Size;
var relativeSpeed = 0.01;
var horizontalSpeed = screenResolution.Width * relativeSpeed;

另外,有几条评论:

  1. Invalidate()处理程序中使用Refresh()代替Tick

  2. 要获得无闪烁的动画,请确保在构造函数中正确配置ControlStyles标志:

    public MainForm()
    {
        InitializeComponent();
    
        SetStyle(ControlStyles.AllPaintingInWmPaint | 
            ControlStyles.OptimizedDoubleBuffer | 
            ControlStyles.ResizeRedraw |
            ControlStyles.UserPaint, true);
    }