C# 将方形图片剪切为圆形(winForm)

先上图片看效果,(圆形图片大小可调)

示例图片:
C# 将方形图片剪切为圆形(winForm)

 

后台代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Pircutre
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //上传图片显示
        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //PictureBox控件显示图片
                pictureBox1.ImageLocation = openFileDialog1.FileName;
                //PictureBox.Load(openFileDialog1.FileName);
            }
        }

        //将图片转换为圆形
        private void button1_Click(object sender, EventArgs e)
        {
            Image image = this.pictureBox1.Image;
            Image newImage = CutEllipse(image, new Rectangle(0, 0, 200, 200), new Size(150, 150));
            this.pictureBox2.Image = newImage;
        }

        //转换为圆形的方法
        private Image CutEllipse(Image img, Rectangle rec, Size size)
        {
            Bitmap bitmap = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                using (TextureBrush br = new TextureBrush(img,System.Drawing.Drawing2D.WrapMode.Clamp, rec))
                {
                    br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.FillEllipse(br, new Rectangle(Point.Empty, size));
                }
            }
            return bitmap;
        }


    }
}