有趣的事

c# 中如何实现控件内图片旋转?

在C#中,你可以使用Graphics类和PictureBox控件来实现控件内图片的旋转。以下是一个示例代码:

private void RotateImage(Control control, Image image, float angle)
{
    // 创建一个新的位图,并将其作为控件的背景图
    Bitmap rotatedImage = new Bitmap(control.Width, control.Height);
    control.BackgroundImage = rotatedImage;

    // 使用Graphics对象绘制旋转后的图片
    using (Graphics g = Graphics.FromImage(rotatedImage))
    {
        g.TranslateTransform(control.Width / 2, control.Height / 2);  // 将坐标原点移动到控件中心
        g.RotateTransform(angle);  // 旋转图片
        g.TranslateTransform(-control.Width / 2, -control.Height / 2);  // 将坐标原点移回左上角
        g.DrawImage(image, new Point(0, 0));  // 绘制旋转后的图片
    }
}

你可以在需要旋转图片的事件中调用这个方法,例如在按钮点击事件中:

private void btnRotate_Click(object sender, EventArgs e)
{
    // 传入需要旋转的控件、图片和角度
    RotateImage(pictureBox1, pictureBox1.Image, 45);
}

这个示例代码会将PictureBox控件中的图片旋转45度,并将旋转后的图片作为控件的背景图显示出来。你可以根据需要修改角度和控件类型。

相关阅读