1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| public Bitmap CreateCroppedImage(Bitmap image, double left, double top, double width, double height, ShapeType shapeType) { Bitmap result = new Bitmap(image.Width, image.Height); using (Graphics g = Graphics.FromImage(result)) { RectangleF srcRect = new Rectangle((int)left, (int)top, (int)width, (int)height);
switch (shapeType) { case ShapeType.Rectangle: g.DrawImage(image, new Rectangle(0, 0, result.Width, result.Height), srcRect, GraphicsUnit.Pixel); break; case ShapeType.Ellipse: { int x = (int)width / 2; int y = (int)height / 2;
g.SmoothingMode = SmoothingMode.AntiAlias; g.TranslateTransform(result.Width / 2, result.Height / 2); GraphicsPath gp = new GraphicsPath(); gp.AddEllipse(0 - x, 0 - y, result.Width, result.Height); Region rg = new Region(gp); g.SetClip(rg, CombineMode.Replace);
g.DrawImage(image, new Rectangle(-x, -y, result.Width, result.Height), srcRect, GraphicsUnit.Pixel); } break; case ShapeType.Triangle: { float x1 = 0; float y1 = 0; float x2 = (float)(x1 + width); float y2 = (float)(y1 + height);
PointF[] destPoints = { new PointF(x1 + (x2 - x1) / 2, y1), new PointF(x2, y2), new PointF(x1, y2), };
GraphicsPath gp = new GraphicsPath(); gp.AddPolygon(destPoints); Region region = new Region(gp); g.SetClip(region, CombineMode.Replace);
g.DrawImage(image, new Rectangle(0, 0, result.Width, result.Height), srcRect, GraphicsUnit.Pixel); } break; } }
return result; }
|