2022年圣诞节到来啦,很高兴这次我们又能一起度过~ 本文会基于C# GDI+技术 实现魔法圣诞树效果!源码和素材在文末全部都有!
对于圣诞树,网上各像编程语言像python、css、java、c/c++都有见到过了,那么在绘图方面,还有一位实力强劲的语言,那就C#语言,它的GDI+技术也可以称的上是笑傲江湖,但网上鲜见C#代码画的圣诞树,所以今天我就使用 C# 代码 来 展示一下 它的实力,挑战画一颗带魔法圣诞树:树会自动成长,树上挂件会不断变换,就像有魔法一样~

这是画整颗树的“一段”的方法:
private void DrawTreeLayer(Graphics g, int start, int end, ref int x, ref int y)
{
using (Brush brush = new SolidBrush(Color.FromArgb(9, 124, 37)))
{
int outSize = rectSize + border;
bool lastFillImage = false;
for (int i = start; i <= end; i++)
{
for (int j = 0; j < (i * 2 - 1); j++)
{
if (j == 0)
{
// 画最左边
DrawTreeLeft(g, brush, x, y, rectSize, rectSize);
}
else if (j == i * 2 - 2)
{
// 画最右边
DrawTreeRight(g, brush, x, y, rectSize, rectSize);
}
else
{
// 画树上的小装饰挂件
g.FillRectangle(brush, x, y, rectSize, rectSize);
if (lastFillImage || i == start)
{
lastFillImage = false;
}
else
{
lastFillImage = DrawGift(g, brush, x, y, rectSize, rectSize);
}
}
x += outSize;
}
x = startX - i * outSize;
y += outSize;
}
}
}那么多少段是根据成长值动态计算出来的,所以我们在OnPaint里来通过level指定,再调用DrawTreeLayer实现
int x = startX;
int y = startY;
int outSize = rectSize + border;
for (int i = 4; i < 3 + level; i++)
{
// 一层比一层低的设置
int start = 2 + i - 4;
int end = i;
x = startX - (start - 1) * (rectSize + border);
DrawTreeLayer(g, start, end, ref x, ref y);
}
x = startX - (rectSize + border);
DrwaRoot(g, ref x, ref y);画树根就很简单了
// 画树根
private void DrwaRoot(Graphics g, ref int x, ref int y)
{
using (Brush brush = new SolidBrush(Color.FromArgb(131, 78, 0)))
{
int outSize = rectSize + border;
for (int i = 0; i < rootHeight; i++)
{
for (int j = 0; j < rootWidth; j++)
{
g.FillRectangle(brush, x, y, rectSize, rectSize);
x += outSize;
}
x = startX - outSize;
y += outSize;
}
}
}利用GDI+的路径(GraphicsPath)画了一颗小星星
// 画星星
Color[] starColors = new Color[] { Color.Yellow, Color.Cyan, ColorTranslator.FromHtml("#FFDF00") };
int curStarColorIndex = 0;
private void DrawStar(Graphics g, Point center, float angle, int radius)
{
PointF[] points = new PointF[]
{
new PointF(center.X, center.Y - radius),
new PointF((float)(center.X + radius * Math.Sin(72 * Math.PI / 180)), (float)(center.Y - radius * Math.Cos(72 * Math.PI / 180))),
new PointF((float)(center.X + radius * Math.Sin(36 * Math.PI / 180)), (float)(center.Y + radius * Math.Cos(36* Math.PI / 180))),
new PointF((float)(center.X - radius * Math.Sin(36 * Math.PI / 180)),(float)( center.Y + radius * Math.Cos(36 * Math.PI / 180))),
new PointF((float)(center.X - radius * Math.Sin(72 * Math.PI / 180)), (float)(center.Y - radius * Math.Cos(72 * Math.PI / 180))),
};
GraphicsPath path = new GraphicsPath(FillMode.Winding);
path.AddLine(points[0], points[2]);
path.AddLine(points[2], points[4]);
path.AddLine(points[4], points[1]);
path.AddLine(points[1], points[3]);
path.AddLine(points[3], points[0]);
path.CloseFigure();
g.RotateTransform(angle);
// 画白边框
using (Pen pen = new Pen(Color.White, 6f))
{
path.GetBounds().Inflate(6, 6);
g.DrawPath(pen, path);
path.GetBounds().Inflate(-6, -6);
}
// 填充色轮换
using (Brush brush = new SolidBrush(starColors[curStarColorIndex]))
{
g.FillPath(brush, path);
}
int nextStarColorIndex = (curStarColorIndex == starColors.Length - 1) ? 0 : (curStarColorIndex + 1);
curStarColorIndex = nextStarColorIndex;
}更有层次感,所以对左边线和右边线,也做了处理,开始是单纯的画直角三角形,但是太直了,所以改为画多边形效果就好很多,像有雪压在上面的效果~// 画树左边
private void DrawTreeLeft(Graphics g, Brush brush, int x, int y, int width, int height)
{
PointF point1 = new PointF(x + width, y);
PointF point2 = new PointF(x + z12, y + height - z12);
PointF point3 = new PointF(x - z16, y + height);
PointF point4 = new PointF(x + width, y + height);
PointF[] fillPts = { point1, point2, point3, point4 };
g.FillPolygon(brush, fillPts);
// 画白边框
PointF[] borderPts = { point1, point2, point3 };
using (Pen pen = new Pen(Color.White, 3f))
{
g.DrawLines(pen, borderPts);
}
}
// 画树右边
private void DrawTreeRight(Graphics g, Brush brush, int x, int y, int width, int height)
{
PointF point1 = new PointF(x, y);
PointF point2 = new PointF(x, y + height);
PointF point3 = new PointF(x + width + z16, y + height);
PointF point4 = new PointF(x + width - z12, y + height - z12);
PointF[] pntArr = { point1, point2, point3, point4 };
g.FillPolygon(brush, pntArr);
// 画白边框
PointF[] borderPts = { point1, point4, point3 };
using (Pen pen = new Pen(Color.White, 3f))
{
g.DrawLines(pen, borderPts);
}
}32张png小图片,直接画图片,但这里也有一个小细节,png背景是白色,如果原样画图片,会很不和谐,所以需要把白色变透明,请看代码:加载32张png小图片,你可以把你想加的放到iconfont目录即可:
string[] files = Directory.GetFiles("iconfont\\");
foreach (string file in files)
{
Image img = Image.FromFile(file);
Bitmap bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(img, 0, 0, img.Width, img.Height);
}
bmp.MakeTransparent(Color.White);
bitmapList.Add(bmp);
}
this.backImage = Image.FromFile("backgroud\\backgroud.jpg");画树上的小装饰挂件方法:
// 画树上的小装饰挂件
private bool DrawGift(Graphics g, Brush brush, int x, int y, int width, int height)
{
byte[] buffer = Guid.NewGuid().ToByteArray();
int iSeed = BitConverter.ToInt32(buffer, 0);
Random random = new Random(iSeed);
int i = random.Next(bitmapList.Count * 2);
if (i < bitmapList.Count)
{
Rectangle destRect = new Rectangle(x, y, width, height);
Rectangle srcRect = new Rectangle(0, 0, bitmapList[i].Width, bitmapList[i].Height);
g.DrawImage(bitmapList[i], destRect, srcRect, GraphicsUnit.Pixel);
return true;
}
return false;
}小细节,如何把背景图片模糊化,这样才好突显树的效果,我这里是做了透明度处理:this.backImage = Image.FromFile("backgroud\\backgroud.jpg");
// 画背景图片带透明度
using (ImageAttributes attributes = GetAlphaImgAttr(50))
{
Rectangle destRect = new Rectangle(0, 0, this.Width, this.Height);
g.DrawImage(this.backImage, destRect, 0, 0, this.backImage.Width, this.backImage.Height, GraphicsUnit.Pixel, attributes);
}获取一个带有透明度的ImageAttributes
public ImageAttributes GetAlphaImgAttr(int opcity)
{
if (opcity < 0 || opcity > 100)
{
throw new ArgumentOutOfRangeException("opcity 值为 0~100");
}
//颜色矩阵
float[][] matrixItems =
{
new float[]{
1,0,0,0,0},
new float[]{
0,1,0,0,0},
new float[]{
0,0,1,0,0},
new float[]{
0,0,0,(float)opcity / 100,0},
new float[]{
0,0,0,0,1}
};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
ImageAttributes imageAtt = new ImageAttributes();
imageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
return imageAtt;
}// 当前刷新次数
int curRefreshCount = 0;
// 成长阀值
int growThreshold = 9;
private void timer1_Tick(object sender, EventArgs e)
{
this.Refresh();
curRefreshCount++;
// 刷新次数超过growThreshold长一次高度
if (curRefreshCount >= growThreshold)
{
curRefreshCount = 0;
if (level >= 8)
{
//level = 3;
this.startY = 100 + (8 - level) * 3 * rectSize;
}
else
{
this.level++;
this.startY -= 3 * rectSize;
}
}
}打包下载地址:https://download.csdn.net/download/scm_2008/87342631
最后祝大家Merry Christmas~
大家有什么好的建议或想法,欢迎评论区讨论.
创作不易,求关注,点赞,收藏,谢谢~