2010年7月4日 星期日

[.NET] How to implement rotate image in user control.

Introduction
Sometimes we need to rotate image in user control.
I override OnPaint method, and use Graphics.RotateTransform to rotate image.

Source Code
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.Default;
Rectangle rect=new Rectangle(0,0,this.Width,this.Height);
PointF center=new PointF(rect.Width/2,rect.Height/2);

float offsetX=0;
float offsetY=0;
offsetX = center.X - DoorWidth / 2;
offsetY = center.Y - DoorHeight / 2;
picRect = new RectangleF(offsetX, offsetY, DoorWidth, DoorHeight);
PointF Pcenter=new PointF(picRect.X+picRect.Width/2,
picRect.Y+picRect.Height/2);

e.Graphics.TranslateTransform(Pcenter.X, Pcenter.Y);
e.Graphics.RotateTransform(-m_i4Angle);

e.Graphics.TranslateTransform(-Pcenter.X, -Pcenter.Y);
if (m_bIsOpened)
{
int t_i4doorWidth = (DoorWidth - DoorOpenWidth) / 2;
RectangleF picRect1 = new RectangleF(offsetX, offsetY, t_i4doorWidth, DoorHeight);
e.Graphics.FillRectangle(new SolidBrush(m_OpenColor), picRect1);
RectangleF picRect2 = new RectangleF(offsetX + DoorOpenWidth + t_i4doorWidth, offsetY, t_i4doorWidth, DoorHeight);
e.Graphics.FillRectangle(new SolidBrush(m_OpenColor), picRect2);
}
else
{
e.Graphics.FillRectangle(new SolidBrush(m_CloseColor), picRect);
}
e.Graphics.ResetTransform();
}



Image

沒有留言:

張貼留言

Hello