原理如下:
GDI+提供了画圆,但是没有提供去掉四角多余的方法。
那么我们可以将图像画到一个Bitmap上,可以创建一个无色透明的bitmap,当成画布,
然后将图像画到用圆形的方式画到新的无色的bitmap上,自然就相当于去掉了四个角多余的部分,
然后将这个无色背景画了图像的bitmap再与其他背景合并,就得到了圆形的图像。
Bitmap bg= new Bitmap(500,1000); Graphics g = Graphics.FromImage(bg); //先画一张背景图 500*1000的 g.Clear(Color.White);//给画布染色 如果bitmap是图片,则不需要上色 Bitmap bmp = new Bitmap(model.HeadImgPath); //准备头像 Bitmap bitmap = new Bitmap(220, 220); //准备一个正方形,得到一个画了头像的图片,无论头像多大,要画到这个正方形上来 using (Graphics g3 = Graphics.FromImage(bitmap)) { using (TextureBrush br = new TextureBrush(bmp, WrapMode.Clamp, new Rectangle(0,0, bmp.Width, bmp.Width))) { br.ScaleTransform(bitmap.Width / (float)bmp.Width, bitmap.Height / (float)bmp.Width); g3.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g3.FillEllipse(br, new Rectangle(Point.Empty, new Size(220, 220)));//将头像以圆形画到另一个图上 } } Rectangle theRectangle = new Rectangle(50, 50,220, 220); //再把正方形画到背景画布上 g.DrawImage(bitmap, theRectangle);
留下您的脚步
最近评论