Graphics 小记
1.切图
drowg.DrawImage(productImg1, new System.Drawing.Rectangle(30, 30, 300, 300), new System.Drawing.Rectangle(0, 0, 100, 100), System.Drawing.GraphicsUnit.Pixel);
2个Rectangle的理解。之前对这个理解有误。(将2个区域的作用理解反了。)
来理解下这2个Rectangle的意思。。先看第二个
第二个Rectangle。( new System.Drawing.Rectangle(0, 0, 100, 100))
切图,表示将原图从x:0,y:0的位置进行剪切w:100,h:100。
第一个Rectangle。( new System.Drawing.Rectangle(30, 30, 300, 300))
填充,表示将第二个Rectangle的区域填充至x:30,y:30的位置。并设置w:300,h:300.进行伸缩。
2.旋转
需求:在画布中完成图片旋转的功能,网上倒是有很多但都不合意。下面是我用的方法:
public static void DrawImg(this Bitmap canvas, int angle, Image img, int imgX, int imgY, int imgW, int imgH) { var g1 = Graphics.FromImage(canvas); g1.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g1.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //计算X,Y的原点 var pointX = imgX + imgW / 2; var pointY = imgY + imgH / 2; g1.TranslateTransform(pointX, pointY); //旋转角度 g1.RotateTransform(angle); //恢复原点 g1.TranslateTransform(-pointX, -pointY); //画图 g1.DrawImage(img, new System.Drawing.Rectangle(imgX, imgY, imgW, imgH)); g1.ResetTransform(); }
调用:
canvas.DrawImg(0, productImg1, 0, 0, 300, 300); canvas.DrawImg(20, productImg2, 0, 0, 100, 100); canvas.DrawImg(30, productImg3, 100, 100, 200, 200); canvas.DrawImg(240, productImg4, 200, 200, 300, 300); canvas.DrawImg(350, productImg5, 300, 300, 150, 150);