码迷,mamicode.com
首页 > Windows程序 > 详细

WPF文字描边的解决方法

时间:2015-05-13 21:53:00      阅读:715      评论:0      收藏:0      [点我收藏+]

标签:wpf   文字描边   炫酷效果   



由于项目原因,今天研究了一下午WPF的文字描边,网上这方面的资料奇少,搞了半天才发现强大的WPF原来不直接支持文字描边啊。最后求助于MSDN,找到了方案,和大家分享一下:


主要思路:FormattedText将字符串转换为Geometry,再在重写的OnRender(DrawingContext drawingContext)方法中绘制Geometry效果如图。

技术分享

组件的主要属性:

Text属性设置文字

Fill属性设置文本本身的画刷

Stroke属性是描边画刷

StrokeThicknes是描边宽度

其他属性同Label(继承自Label)

核心代码:

        private void getformattedText(string str)
        {
            // Create the formatted text based on the properties set.
            FormattedText formattedText = new FormattedText(
                str,
                CultureInfo.GetCultureInfo("en-us"),
                FlowDirection.LeftToRight,
                new Typeface(
                    FontFamily,
                    FontStyle,
                    FontWeight,
                    FontStretch),
                FontSize,
                System.Windows.Media.Brushes.Black // This brush does not matter since we use the geometry of the text. 
                );

            this.Width = formattedText.Width;
            this.Height = formattedText.Height;
            // Build the geometry object that represents the text.
            //pg.AddGeometry(formattedText.BuildGeometry(new System.Windows.Point(5, 5)));
            TextGeometry = formattedText.BuildGeometry(new System.Windows.Point(0,0));
            // Build the geometry object that represents the text hightlight.
            if (Highlight == true)
            {
                TextHighLightGeometry = formattedText.BuildHighlightGeometry(new System.Windows.Point(0, 0));
            }
        }

        /// <summary>
        /// OnRender override draws the geometry of the text and optional highlight.
        /// </summary>
        /// <param name="drawingContext">Drawing context of the OutlineText control.</param>
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            CreateText();
            // Draw the outline based on the properties that are set.
            drawingContext.DrawGeometry(Fill, new System.Windows.Media.Pen(Stroke, StrokeThickness), TextGeometry);
            // Draw the text highlight based on the properties that are set.
            if (Highlight == true)
            {
                drawingContext.DrawGeometry(null, new System.Windows.Media.Pen(Stroke, StrokeThickness), TextHighLightGeometry);
            }
        }

具体代码请参照如下资源:

http://download.csdn.net/detail/wblct/8697005

需要2分的资源分,快没分了,大家谅解啊。

WPF文字描边的解决方法

标签:wpf   文字描边   炫酷效果   

原文地址:http://blog.csdn.net/springberlin/article/details/45699625

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!