C# graphics.drawimage center resize [C# 按鈕(Button) 重繪(繪圖/override OnPaint) 圖片至中 & 重新計算圖片大小]

C# graphics.drawimage center resize [C# 按鈕(Button) 重繪(繪圖/override OnPaint) 圖片至中 & 重新計算圖片大小]

C# graphics.drawimage center resize [C# 按鈕(Button) 重繪(繪圖/override OnPaint) 圖片至中 & 重新計算圖片大小]


ChatGPT回答

To draw an image at the center of a container with resizing in C#, you can use the Graphics.DrawImage method along with some calculations to determine the position and size of the image.

Here's an example code snippet that shows how to achieve this:

csharp
Copy code
// Load the image file
Image originalImage = Image.FromFile("image.jpg");

// Get the container size
int containerWidth = containerControl.ClientSize.Width;
int containerHeight = containerControl.ClientSize.Height;

// Calculate the position and size of the image
int imageWidth, imageHeight, x, y;
if (originalImage.Width > containerWidth || originalImage.Height > containerHeight)
{
    double aspectRatio = (double)originalImage.Width / originalImage.Height;
    if (originalImage.Width > originalImage.Height)
    {
        imageWidth = containerWidth;
        imageHeight = (int)(containerWidth / aspectRatio);
    }
    else
    {
        imageHeight = containerHeight;
        imageWidth = (int)(containerHeight * aspectRatio);
    }
}
else
{
    imageWidth = originalImage.Width;
    imageHeight = originalImage.Height;
}
x = (containerWidth - imageWidth) / 2;
y = (containerHeight - imageHeight) / 2;

// Draw the image
using (Graphics g = containerControl.CreateGraphics())
{
    g.DrawImage(originalImage, x, y, imageWidth, imageHeight);
}
In this example, we first load the original image from a file. Then, we get the size of the container control where we want to draw the image. We use some calculations to determine the position and size of the image based on the container size and the aspect ratio of the original image. Finally, we use the Graphics.DrawImage method to draw the image at the calculated position and size.

Note that in this example, we are using the CreateGraphics method of the container control to get a Graphics object for drawing the image. This is just one way of getting a Graphics object in C#, and the actual method may depend on the specific context where you want to draw the image.

自己應用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using static System.Net.Mime.MediaTypeNames;
using System.Windows.Forms;

namespace Vteam_UserControl
{
    public enum ControlState { Hover, Normal, Pressed }
    public class RoundButton : Button
    {

        public int m_intSID;
        public bool m_blnclicked;
        private int radius;//半徑 
        private Color _baseColor = Color.FromArgb(51, 161, 224);//基顏色
        private Color _hoverColor = Color.FromArgb(51, 0, 224);//基顏色
        private Color _normalColor = Color.FromArgb(0, 161, 224);//基顏色
        private Color _disnormalColor = Color.FromArgb(136, 222, 255);//停用基顏色
        private Color _pressedColor = Color.FromArgb(51, 161, 0);//基顏色
        //圓形按鈕的半徑屬性
        [CategoryAttribute("佈局"), BrowsableAttribute(true), ReadOnlyAttribute(false)]
        public int Radius
        {
            set
            {
                radius = value;
                this.Invalidate();
            }
            get
            {
                return radius;
            }
        }
        [DefaultValue(typeof(Color), "51, 161, 224")]
        public Color NormalColor
        {
            get
            {
                return this._normalColor;
            }
            set
            {
                this._normalColor = value;
                this.Invalidate();
            }
        }

        public Color DisNormalColor
        {
            get
            {
                return this._disnormalColor;
            }
            set
            {
                this._disnormalColor = value;
                this.Invalidate();
            }
        }

        //  [DefaultValue(typeof(Color), "220, 80, 80")]
        public Color HoverColor
        {
            get
            {
                return this._hoverColor;
            }
            set
            {
                this._hoverColor = value;
                this.Invalidate();
            }
        }

        //  [DefaultValue(typeof(Color), "251, 161, 0")]
        public Color PressedColor
        {
            get
            {
                return this._pressedColor;
            }
            set
            {
                this._pressedColor = value;
                this.Invalidate();
            }
        }
        public ControlState ControlState { get; set; }
        protected override void OnMouseEnter(EventArgs e)//鼠標進入時
        {
            base.OnMouseEnter(e);
            if (!m_blnclicked)
            {
                ControlState = ControlState.Hover;//正常
            }
            else
            {
                ControlState = ControlState.Pressed;//按下的狀態
            }
        }
        protected override void OnMouseLeave(EventArgs e)//鼠標離開
        {
            base.OnMouseLeave(e);
            if(!m_blnclicked)
            {
                ControlState = ControlState.Normal;//正常
            }
            else
            {
                ControlState = ControlState.Pressed;//按下的狀態
            }
            
        }
        protected override void OnMouseDown(MouseEventArgs e)//鼠標按下
        {
            base.OnMouseDown(e);
            if (e.Button == MouseButtons.Left && e.Clicks == 1)//鼠標左鍵且點擊次數爲1
            {
                ControlState = ControlState.Pressed;//按下的狀態
                m_blnclicked = true;
            }
        }
        protected override void OnMouseUp(MouseEventArgs e)//鼠標彈起
        {
            base.OnMouseUp(e);
            /*
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
                if (ClientRectangle.Contains(e.Location))//控件區域包含鼠標的位置
                {
                    ControlState = ControlState.Hover;
                }
                else
                {
                    ControlState = ControlState.Normal;
                }
            }
            */
        }
        public RoundButton()
        {
            m_intSID=0;
            m_blnclicked =false;

            Radius = 15;
            this.FlatStyle = FlatStyle.Flat;
            this.FlatAppearance.BorderSize = 0;
            this.ControlState = ControlState.Normal;
            this.SetStyle(
             ControlStyles.UserPaint |  //控件自行繪製,而不使用操作系統的繪製
             ControlStyles.AllPaintingInWmPaint | //忽略擦出的消息,減少閃爍。
             ControlStyles.OptimizedDoubleBuffer |//在緩衝區上繪製,不直接繪製到屏幕上,減少閃爍。
             ControlStyles.ResizeRedraw | //控件大小發生變化時,重繪。                  
             ControlStyles.SupportsTransparentBackColor, true);//支持透明背景顏色
        }

        private Color GetColor(Color colorBase, int a, int r, int g, int b)
        {
            int a0 = colorBase.A;
            int r0 = colorBase.R;
            int g0 = colorBase.G;
            int b0 = colorBase.B;
            if (a + a0 > 255) { a = 255; } else { a = Math.Max(a + a0, 0); }
            if (r + r0 > 255) { r = 255; } else { r = Math.Max(r + r0, 0); }
            if (g + g0 > 255) { g = 255; } else { g = Math.Max(g + g0, 0); }
            if (b + b0 > 255) { b = 255; } else { b = Math.Max(b + b0, 0); }

            return Color.FromArgb(a, r, g, b);
        }

        //重寫OnPaint
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            base.OnPaint(e);
            base.OnPaintBackground(e);
            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;

            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;

            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
            var path = GetRoundedRectPath(rect, radius);

            this.Region = new Region(path);

            Color baseColor;
            //Color borderColor;
            //Color innerBorderColor = this._baseColor;//Color.FromArgb(200, 255, 255, 255); ;

            switch (ControlState)
            {
                case ControlState.Hover:
                    if (this.Enabled)
                    {
                        baseColor = this.HoverColor;
                    }
                    else
                    {
                        baseColor = this.DisNormalColor;
                    }
                    break;
                case ControlState.Pressed:
                    if (this.Enabled)
                    {
                        baseColor = this.PressedColor;
                    }
                    else
                    {
                        baseColor = this.DisNormalColor;
                    }
                    break;
                case ControlState.Normal:
                    if (this.Enabled)
                    {
                        baseColor = this.NormalColor;
                    }
                    else
                    {
                        baseColor = this.DisNormalColor;
                    }
                    break;
                default:
                    if (this.Enabled)
                    {
                        baseColor = this.NormalColor;
                    }
                    else
                    {
                        baseColor = this.DisNormalColor;
                    }
                    break;
            }

            using (SolidBrush b = new SolidBrush(baseColor))
            {
                e.Graphics.FillPath(b, path);
                Font fo = new System.Drawing.Font("Microsoft JhengHei UI", 14, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
                Brush brush;
                if (this.Enabled)
                {
                    brush = new SolidBrush(this.ForeColor);
                }
                else
                {
                    brush = new SolidBrush(Color.FromArgb(128,128,128));
                }
                StringFormat gs = new StringFormat();
                gs.Alignment = StringAlignment.Center; //居中
                gs.LineAlignment = StringAlignment.Center;//垂直居中

                // Draw the background image if it is set [參考ChatGPT]
                if (Image != null)
                {
                    // Get the container size
                    int containerWidth = ClientRectangle.Width;
                    int containerHeight = ClientRectangle.Height;

                    // Calculate the position and size of the image
                    int imageWidth, imageHeight, x, y;
                    if (Image.Width > containerWidth || Image.Height > containerHeight)
                    {
                        double aspectRatio = (double)Image.Width / Image.Height;
                        if (containerWidth < containerHeight)
                        {
                            imageWidth = containerWidth;
                            imageHeight = (int)(containerWidth / aspectRatio);
                        }
                        else
                        {
                            imageHeight = containerHeight;
                            imageWidth = (int)(containerHeight * aspectRatio);
                        }
                    }
                    else
                    {
                        imageWidth = Image.Width;
                        imageHeight = Image.Height;
                    }
                    x = (containerWidth - imageWidth) / 2;
                    y = (containerHeight - imageHeight) / 2;

                    e.Graphics.DrawImage(Image, x, y, imageWidth, imageHeight);//e.Graphics.DrawImage(Image, ClientRectangle);
                }

                e.Graphics.DrawString(this.Text, this.Font, brush, rect, gs);
                //  e.Graphics.DrawPath(p, path);
            }
        }
        private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)
        {
            int diameter = radius;
            Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
            GraphicsPath path = new GraphicsPath();
            path.AddArc(arcRect, 180, 90);
            arcRect.X = rect.Right - diameter;
            path.AddArc(arcRect, 270, 90);
            arcRect.Y = rect.Bottom - diameter;
            path.AddArc(arcRect, 0, 90);
            arcRect.X = rect.Left;
            path.AddArc(arcRect, 90, 90);
            path.CloseFigure();
            return path;
        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
        }
    }
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *