LockBits image rotation method not working?

后端 未结 1 687
梦谈多话
梦谈多话 2020-12-12 07:48

Hey all. I resorted to using LockBits for 2d bitmap image rotation after getting fed up with the slow performance and wacky behavior of both Get/Set Pixel, and RotateTransfo

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 08:18

    You are digging yourself a deeper hole. This goes wrong early, the size of the rotated bitmap is not Width x Height. It is also very inefficient. You need to get RotateTransform going, it is important to also use TranslateTransform and pick the correct image drawing location.

    Here's a sample Windows Forms app that rotates a bitmap around its center point, offset just enough to touch the inner edge of the form when it rotates. Drop a Timer on the form and add an image resource with Project + Properties, Resource tab. Name it SampleImage, it doesn't have to be square. Make the code look like this:

    public partial class Form1 : Form {
        private float mDegrees;
        private Image mBmp;
        public Form1() {
            InitializeComponent();
            mBmp = Properties.Resources.SampleImage;
            timer1.Enabled = true;
            timer1.Interval = 50;
            timer1.Tick += new System.EventHandler(this.timer1_Tick);
            this.DoubleBuffered = true;
        }
        private void timer1_Tick(object sender, EventArgs e) {
            mDegrees += 3.0F;
            this.Invalidate();
        }
        protected override void OnPaint(PaintEventArgs e) {
            int center = (int)Math.Sqrt(mBmp.Width * mBmp.Width + mBmp.Height * mBmp.Height) / 2;
            e.Graphics.TranslateTransform(center, center);
            e.Graphics.RotateTransform(mDegrees);
            e.Graphics.DrawImage(mBmp, -mBmp.Width/2, -mBmp.Height/2);
        }
    }
    

    You can make draw a lot faster by creating a bitmap in the 32bppPArgb format, I skipped that step.

    0 讨论(0)
提交回复
热议问题