代码改变世界

Silverlight 字体描边

2010-09-18 00:14  平凡主义  阅读(2340)  评论(8编辑  收藏  举报

  最近一段时间纠结于SL的字体描边上面,由于游戏地图的色彩很丰富。将字体放在页面上的时候会发现在某些区域出现看不见字体。 于是就打算将字体进行一个描边,网上找了很久似乎SL不支持字体描边。于是只有自己写一个啦。

  实现思路:

  1.将TextBlock 转换为WriteableBitmap

  2.对WriteableBitmap 的Pixels 进行循环,判断每一个像素点的值最终达到描边的效果。

 

  效果:为了能过看的更清楚我将背景颜色和字体颜色都设置了为白色,而描边效果设置成了黑色。最终效果如下

接下来直接上代码:

 

实现代码
1 //申明一个需要描边的textBlock
2   TextBlock textBlock = new TextBlock() { Text = "描边", FontSize = 300, Foreground = new SolidColorBrush(Colors.White) };
3 //创建WriteableBitmap
4   WriteableBitmap wb = new WriteableBitmap(textBlock, null);
5 //将textblock 转换为WriteableBitmap
6   wb.Render(textBlock, null);
7 //绘制
8   wb.Invalidate();
9
10 //得到图片的宽高
11   int width = wb.PixelWidth;
12 int height = wb.PixelHeight;
13 //描边颜色
14 Color color = Colors.Black;
15 //描边rgba 值
16 byte[] rgbs = new byte[] { color.B, color.G, color.R, color.A };
17 //rgb 值
18 int rgb = BitConverter.ToInt32(rgbs, 0);
19 //循环wb
20 for (int y = 0; y < height; y++)
21 {
22 for (int x = 0; x < width; x++)
23 {
24 //当前行
25 int temp = y * width;
26 //判断是否为第一行
27 if (y > 0)//
28 {
29 //得到当前像素点的值
30 int pixel = wb.Pixels[temp + x];
31 //判断该像素点是否为透明
32 if (pixel != 0)
33 {
34 //得到当前像素点的上一行的值
35 int pixel1 = wb.Pixels[temp - width + x];
36 //如果为透明的话进行填充颜色
37 if (pixel1 == 0)
38 {
39 wb.Pixels[temp - width + x] = BitConverter.ToInt32(rgbs, 0);
40 }
41
42 }
43
44 }
45 //是否是最后一行
46 if (y < height -1)//
47 {
48 int pixel = wb.Pixels[temp + x];
49
50 if (pixel != 0 && pixel != rgb)
51 {
52 int pixel1 = wb.Pixels[temp + width + x];
53 if (pixel1 == 0 && pixel != rgb)
54 {
55 wb.Pixels[temp + width + x] = BitConverter.ToInt32(rgbs, 0);
56 }
57
58 }
59
60 }
61 //
62 if (x > 0)
63 {
64 int pixel = wb.Pixels[temp + x];
65 if (pixel != 0 && pixel != rgb)
66 {
67 int pixel1 = wb.Pixels[temp + x-1];
68 if (pixel1 == 0 && pixel != rgb)
69 {
70 wb.Pixels[temp + x-1] = BitConverter.ToInt32(rgbs, 0);
71 }
72
73 }
74 }
75 //
76 if (x < width-1)
77 {
78 int pixel = wb.Pixels[temp + x];
79 if (pixel != 0 && pixel != rgb)
80 {
81 int pixel1 = wb.Pixels[temp + x + 1];
82 if (pixel1 == 0 && pixel != rgb)
83 {
84 wb.Pixels[temp + x + 1] = BitConverter.ToInt32(rgbs, 0);
85 }
86
87 }
88 }
89 }
90 }
91
92 //生成img
93 Image img = new Image() { Source = wb, Stretch = Stretch.None };
94 //添加显示
95 LayoutRoot.Children.Add(img);
96 //设置背景
97 LayoutRoot.Background = new SolidColorBrush(Colors.White);

 

这个描边是我今天突发奇想写出来的,拿出来给大家看看.如果有更好的解决方案,请告诉我让我也参考参考!

 

 

 

谢绝 Ctrl+C  Ctrl+V

博客园首发!