一,需要动态绑定Path

 <UserControl x:Class="Secom.Emx2.SL.Common.Controls.EleSafe.Ele.Line"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400"> <Path x:Name="myline" Stretch="Fill" Width="{Binding Width, ElementName=path, Mode=TwoWay}" Height="{Binding Height, ElementName=path, Mode=TwoWay}"/>
</UserControl>

二,生成Path

  private LineType _lineType = LineType.VLine;
public LineType LineType
{
get
{
return _lineType;
}
set
{
_lineType = value;
var pathString = string.Empty;
var eff = new DropShadowEffect();
eff.BlurRadius = ;
eff.Color = Colors.DarkGray;
eff.ShadowDepth = ;
var conv = new StringToPathGeometryConverter();
switch (_lineType)
{
case LineType.HLine:
eff.Direction = ;
pathString = "M0,0 L131.137,0";
break;
case LineType.VLine:
default:
eff.Direction = ;
pathString = "M87,60 L87,240.178";
break;
} var pathData = conv.Convert(pathString);
myline.SetValue(Path.DataProperty, pathData);
//myline.SetValue(Path.EffectProperty, eff);
}
}

三,字符串转换成Path对象类

     /* ==============================
* Desc:StringToPathGeometry
* Author:hezp
* Date:2014/8/9 17:39:40
* ==============================*/
public class StringToPathGeometryConverter : IValueConverter
{
#region Const & Private Variables
const bool AllowSign = true;
const bool AllowComma = true;
const bool IsFilled = true;
const bool IsClosed = true; IFormatProvider _formatProvider; PathFigure _figure = null; // Figure object, which will accept parsed segments
string _pathString; // Input string to be parsed
int _pathLength;
int _curIndex; // Location to read next character from
bool _figureStarted; // StartFigure is effective Point _lastStart; // Last figure starting point
Point _lastPoint; // Last point
Point _secondLastPoint; // The point before last point char _token; // Non whitespace character returned by ReadToken
#endregion #region Public Functionality
/// <summary>
/// Main conversion routine - converts string path data definition to PathGeometry object
/// </summary>
/// <param name="path">String with path data definition</param>
/// <returns>PathGeometry object created from string definition</returns>
public PathGeometry Convert(string path)
{
if (null == path)
throw new ArgumentException("Path string cannot be null!"); if (path.Length == )
throw new ArgumentException("Path string cannot be empty!"); return parse(path);
} /// <summary>
/// Main back conversion routine - converts PathGeometry object to its string equivalent
/// </summary>
/// <param name="geometry">Path Geometry object</param>
/// <returns>String equivalent to PathGeometry contents</returns>
public string ConvertBack(PathGeometry geometry)
{
if (null == geometry)
throw new ArgumentException("Path Geometry cannot be null!"); return parseBack(geometry);
}
#endregion #region Private Functionality
/// <summary>
/// Main parser routine, which loops over each char in received string, and performs actions according to command/parameter being passed
/// </summary>
/// <param name="path">String with path data definition</param>
/// <returns>PathGeometry object created from string definition</returns>
private PathGeometry parse(string path)
{
PathGeometry _pathGeometry = null; _formatProvider = CultureInfo.InvariantCulture;
_pathString = path;
_pathLength = path.Length;
_curIndex = ; _secondLastPoint = new Point(, );
_lastPoint = new Point(, );
_lastStart = new Point(, ); _figureStarted = false; bool first = true; char last_cmd = ' '; while (ReadToken()) // Empty path is allowed in XAML
{
char cmd = _token; if (first)
{
if ((cmd != 'M') && (cmd != 'm') && (cmd != 'f') && (cmd != 'F')) // Path starts with M|m
{
ThrowBadToken();
} first = false;
} switch (cmd)
{
case 'f':
case 'F':
_pathGeometry = new PathGeometry();
double _num = ReadNumber(!AllowComma);
_pathGeometry.FillRule = _num == ? FillRule.EvenOdd : FillRule.Nonzero;
break; case 'm':
case 'M':
// XAML allows multiple points after M/m
_lastPoint = ReadPoint(cmd, !AllowComma); _figure = new PathFigure();
_figure.StartPoint = _lastPoint;
_figure.IsFilled = IsFilled;
_figure.IsClosed = !IsClosed;
//context.BeginFigure(_lastPoint, IsFilled, !IsClosed);
_figureStarted = true;
_lastStart = _lastPoint;
last_cmd = 'M'; while (IsNumber(AllowComma))
{
_lastPoint = ReadPoint(cmd, !AllowComma); LineSegment _lineSegment = new LineSegment();
_lineSegment.Point = _lastPoint;
_figure.Segments.Add(_lineSegment);
//context.LineTo(_lastPoint, IsStroked, !IsSmoothJoin);
last_cmd = 'L';
}
break; case 'l':
case 'L':
case 'h':
case 'H':
case 'v':
case 'V':
EnsureFigure(); do
{
switch (cmd)
{
case 'l': _lastPoint = ReadPoint(cmd, !AllowComma); break;
case 'L': _lastPoint = ReadPoint(cmd, !AllowComma); break;
case 'h': _lastPoint.X += ReadNumber(!AllowComma); break;
case 'H': _lastPoint.X = ReadNumber(!AllowComma); break;
case 'v': _lastPoint.Y += ReadNumber(!AllowComma); break;
case 'V': _lastPoint.Y = ReadNumber(!AllowComma); break;
} LineSegment _lineSegment = new LineSegment();
_lineSegment.Point = _lastPoint;
_figure.Segments.Add(_lineSegment);
//context.LineTo(_lastPoint, IsStroked, !IsSmoothJoin);
}
while (IsNumber(AllowComma)); last_cmd = 'L';
break; case 'c':
case 'C': // cubic Bezier
case 's':
case 'S': // smooth cublic Bezier
EnsureFigure(); do
{
Point p; if ((cmd == 's') || (cmd == 'S'))
{
if (last_cmd == 'C')
{
p = Reflect();
}
else
{
p = _lastPoint;
} _secondLastPoint = ReadPoint(cmd, !AllowComma);
}
else
{
p = ReadPoint(cmd, !AllowComma); _secondLastPoint = ReadPoint(cmd, AllowComma);
} _lastPoint = ReadPoint(cmd, AllowComma); BezierSegment _bizierSegment = new BezierSegment();
_bizierSegment.Point1 = p;
_bizierSegment.Point2 = _secondLastPoint;
_bizierSegment.Point3 = _lastPoint;
_figure.Segments.Add(_bizierSegment);
//context.BezierTo(p, _secondLastPoint, _lastPoint, IsStroked, !IsSmoothJoin); last_cmd = 'C';
}
while (IsNumber(AllowComma)); break; case 'q':
case 'Q': // quadratic Bezier
case 't':
case 'T': // smooth quadratic Bezier
EnsureFigure(); do
{
if ((cmd == 't') || (cmd == 'T'))
{
if (last_cmd == 'Q')
{
_secondLastPoint = Reflect();
}
else
{
_secondLastPoint = _lastPoint;
} _lastPoint = ReadPoint(cmd, !AllowComma);
}
else
{
_secondLastPoint = ReadPoint(cmd, !AllowComma);
_lastPoint = ReadPoint(cmd, AllowComma);
} QuadraticBezierSegment _quadraticBezierSegment = new QuadraticBezierSegment();
_quadraticBezierSegment.Point1 = _secondLastPoint;
_quadraticBezierSegment.Point2 = _lastPoint;
_figure.Segments.Add(_quadraticBezierSegment);
//context.QuadraticBezierTo(_secondLastPoint, _lastPoint, IsStroked, !IsSmoothJoin); last_cmd = 'Q';
}
while (IsNumber(AllowComma)); break; case 'a':
case 'A':
EnsureFigure(); do
{
// A 3,4 5, 0, 0, 6,7
double w = ReadNumber(!AllowComma);
double h = ReadNumber(AllowComma);
double rotation = ReadNumber(AllowComma);
bool large = ReadBool();
bool sweep = ReadBool(); _lastPoint = ReadPoint(cmd, AllowComma); ArcSegment _arcSegment = new ArcSegment();
_arcSegment.Point = _lastPoint;
_arcSegment.Size = new Size(w, h);
_arcSegment.RotationAngle = rotation;
_arcSegment.IsLargeArc = large;
_arcSegment.SweepDirection = sweep ? SweepDirection.Clockwise : SweepDirection.Counterclockwise;
_figure.Segments.Add(_arcSegment);
//context.ArcTo(
// _lastPoint,
// new Size(w, h),
// rotation,
// large,
// sweep ? SweepDirection.Clockwise : SweepDirection.Counterclockwise,
// IsStroked,
// !IsSmoothJoin
// );
}
while (IsNumber(AllowComma)); last_cmd = 'A';
break; case 'z':
case 'Z':
EnsureFigure();
_figure.IsClosed = IsClosed;
//context.SetClosedState(IsClosed); _figureStarted = false;
last_cmd = 'Z'; _lastPoint = _lastStart; // Set reference point to be first point of current figure
break; default:
ThrowBadToken();
break;
} if (null != _figure)
{
if (_figure.IsClosed)
{
if (null == _pathGeometry)
_pathGeometry = new PathGeometry(); _pathGeometry.Figures.Add(_figure); _figure = null;
first = true;
}
} } if (null != _figure)
{
if (null == _pathGeometry)
_pathGeometry = new PathGeometry(); if (!_pathGeometry.Figures.Contains(_figure))
_pathGeometry.Figures.Add(_figure); }
return _pathGeometry;
} void SkipDigits(bool signAllowed)
{
// Allow for a sign
if (signAllowed && More() && ((_pathString[_curIndex] == '-') || _pathString[_curIndex] == '+'))
{
_curIndex++;
} while (More() && (_pathString[_curIndex] >= '') && (_pathString[_curIndex] <= ''))
{
_curIndex++;
}
} bool ReadBool()
{
SkipWhiteSpace(AllowComma); if (More())
{
_token = _pathString[_curIndex++]; if (_token == '')
{
return false;
}
else if (_token == '')
{
return true;
}
} ThrowBadToken(); return false;
} private Point Reflect()
{
return new Point( * _lastPoint.X - _secondLastPoint.X,
* _lastPoint.Y - _secondLastPoint.Y);
} private void EnsureFigure()
{
if (!_figureStarted)
{
_figure = new PathFigure();
_figure.StartPoint = _lastStart; //_context.BeginFigure(_lastStart, IsFilled, !IsClosed);
_figureStarted = true;
}
} double ReadNumber(bool allowComma)
{
if (!IsNumber(allowComma))
{
ThrowBadToken();
} bool simple = true;
int start = _curIndex; //
// Allow for a sign
//
// There are numbers that cannot be preceded with a sign, for instance, -NaN, but it's
// fine to ignore that at this point, since the CLR parser will catch this later.
//
if (More() && ((_pathString[_curIndex] == '-') || _pathString[_curIndex] == '+'))
{
_curIndex++;
} // Check for Infinity (or -Infinity).
if (More() && (_pathString[_curIndex] == 'I'))
{
//
// Don't bother reading the characters, as the CLR parser will
// do this for us later.
//
_curIndex = Math.Min(_curIndex + , _pathLength); // "Infinity" has 8 characters
simple = false;
}
// Check for NaN
else if (More() && (_pathString[_curIndex] == 'N'))
{
//
// Don't bother reading the characters, as the CLR parser will
// do this for us later.
//
_curIndex = Math.Min(_curIndex + , _pathLength); // "NaN" has 3 characters
simple = false;
}
else
{
SkipDigits(!AllowSign); // Optional period, followed by more digits
if (More() && (_pathString[_curIndex] == '.'))
{
simple = false;
_curIndex++;
SkipDigits(!AllowSign);
} // Exponent
if (More() && ((_pathString[_curIndex] == 'E') || (_pathString[_curIndex] == 'e')))
{
simple = false;
_curIndex++;
SkipDigits(AllowSign);
}
} if (simple && (_curIndex <= (start + ))) // 32-bit integer
{
int sign = ; if (_pathString[start] == '+')
{
start++;
}
else if (_pathString[start] == '-')
{
start++;
sign = -;
} int value = ; while (start < _curIndex)
{
value = value * + (_pathString[start] - '');
start++;
} return value * sign;
}
else
{
string subString = _pathString.Substring(start, _curIndex - start); try
{
return System.Convert.ToDouble(subString, _formatProvider);
}
catch (FormatException except)
{
throw new FormatException(string.Format("Unexpected character in path '{0}' at position {1}", _pathString, _curIndex - ), except);
}
}
} private bool IsNumber(bool allowComma)
{
bool commaMet = SkipWhiteSpace(allowComma); if (More())
{
_token = _pathString[_curIndex]; // Valid start of a number
if ((_token == '.') || (_token == '-') || (_token == '+') || ((_token >= '') && (_token <= ''))
|| (_token == 'I') // Infinity
|| (_token == 'N')) // NaN
{
return true;
}
} if (commaMet) // Only allowed between numbers
{
ThrowBadToken();
} return false;
} private Point ReadPoint(char cmd, bool allowcomma)
{
double x = ReadNumber(allowcomma);
double y = ReadNumber(AllowComma); if (cmd >= 'a') // 'A' < 'a'. lower case for relative
{
x += _lastPoint.X;
y += _lastPoint.Y;
} return new Point(x, y);
} private bool ReadToken()
{
SkipWhiteSpace(!AllowComma); // Check for end of string
if (More())
{
_token = _pathString[_curIndex++]; return true;
}
else
{
return false;
}
} bool More()
{
return _curIndex < _pathLength;
} // Skip white space, one comma if allowed
private bool SkipWhiteSpace(bool allowComma)
{
bool commaMet = false; while (More())
{
char ch = _pathString[_curIndex]; switch (ch)
{
case ' ':
case '\n':
case '\r':
case '\t': // SVG whitespace
break; case ',':
if (allowComma)
{
commaMet = true;
allowComma = false; // one comma only
}
else
{
ThrowBadToken();
}
break; default:
// Avoid calling IsWhiteSpace for ch in (' ' .. 'z']
if (((ch > ' ') && (ch <= 'z')) || !Char.IsWhiteSpace(ch))
{
return commaMet;
}
break;
} _curIndex++;
} return commaMet;
} private void ThrowBadToken()
{
throw new FormatException(string.Format("Unexpected character in path '{0}' at position {1}", _pathString, _curIndex - ));
} static internal char GetNumericListSeparator(IFormatProvider provider)
{
char numericSeparator = ','; // Get the NumberFormatInfo out of the provider, if possible
// If the IFormatProvider doesn't not contain a NumberFormatInfo, then
// this method returns the current culture's NumberFormatInfo.
NumberFormatInfo numberFormat = NumberFormatInfo.GetInstance(provider); // Is the decimal separator is the same as the list separator?
// If so, we use the ";".
if ((numberFormat.NumberDecimalSeparator.Length > ) && (numericSeparator == numberFormat.NumberDecimalSeparator[]))
{
numericSeparator = ';';
} return numericSeparator;
} private string parseBack(PathGeometry geometry)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
IFormatProvider provider = new System.Globalization.CultureInfo("en-us");
string format = null; sb.Append("F" + (geometry.FillRule == FillRule.EvenOdd ? "" : "") + " "); foreach (PathFigure figure in geometry.Figures)
{
sb.Append("M " + ((IFormattable)figure.StartPoint).ToString(format, provider) + " "); foreach (PathSegment segment in figure.Segments)
{
char separator = GetNumericListSeparator(provider); if (segment.GetType() == typeof(LineSegment))
{
LineSegment _lineSegment = segment as LineSegment; sb.Append("L " + ((IFormattable)_lineSegment.Point).ToString(format, provider) + " ");
}
else if (segment.GetType() == typeof(BezierSegment))
{
BezierSegment _bezierSegment = segment as BezierSegment; sb.Append(String.Format(provider,
"C{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "} ",
separator,
_bezierSegment.Point1,
_bezierSegment.Point2,
_bezierSegment.Point3
));
}
else if (segment.GetType() == typeof(QuadraticBezierSegment))
{
QuadraticBezierSegment _quadraticBezierSegment = segment as QuadraticBezierSegment; sb.Append(String.Format(provider,
"Q{1:" + format + "}{0}{2:" + format + "} ",
separator,
_quadraticBezierSegment.Point1,
_quadraticBezierSegment.Point2));
}
else if (segment.GetType() == typeof(ArcSegment))
{
ArcSegment _arcSegment = segment as ArcSegment; sb.Append(String.Format(provider,
"A{1:" + format + "}{0}{2:" + format + "}{0}{3}{0}{4}{0}{5:" + format + "} ",
separator,
_arcSegment.Size,
_arcSegment.RotationAngle,
_arcSegment.IsLargeArc ? "" : "",
_arcSegment.SweepDirection == SweepDirection.Clockwise ? "" : "",
_arcSegment.Point));
}
} if (figure.IsClosed)
sb.Append("Z");
} return sb.ToString();
}
#endregion #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string path = value as string;
if (null != path)
return Convert(path);
else
return null;
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
PathGeometry geometry = value as PathGeometry; if (null != geometry)
return ConvertBack(geometry);
else
return default(string);
} #endregion
}

Silverlight日记:字符串装换成Path对象的更多相关文章

  1. python txt装换成excel

    工作中,我们需要经常吧一些导出的数据文件,例如sql查出来的结果装换成excel,用文件发送.这次为大家带上python装换excel的脚本 记得先安装wlwt模块,适用版本,python2-3 #c ...

  2. js中Json字符串如何转成Json对象(4种转换方式)

    js中Json字符串如何转成Json对象(4种转换方式) 一.总结 一句话总结:原生方法(就是浏览器默认支持的方法) 浏览器支持的转换方式(Firefox,chrome,opera,safari,ie ...

  3. js 一数组分割成若干个数组,并装换成字符串赋个li标签

    success: function (datas) { //请求成功后处理函数. var htmltext = ''; var data = datas.result; console.log(dat ...

  4. Web Api 将DataTable装换成Excel,并通过文件流将其下载

    不废话,直接上代码 前端代码 <input type="button" class="layui-btn" value="Test-GetFil ...

  5. Java读取Excel转换成JSON字符串进而转换成Java对象

    Jar包

  6. 字符串json转成json对象

    方法1 JsonSerializer serializer = new JsonSerializer(); TextReader tr = new StringReader(text); JsonTe ...

  7. Java,double类型转换成String,String装换成double型

    今天,老师布置了小系统,银行用户管理系统,突然发现自己的基础知识好薄弱,就把这些记录一下, double类型转化string:Double.toString(double doub); String类 ...

  8. 将n行3列的数据dataTable装换成m行7列的dataTable

    //思路:新建dataTable,定义需要的列, 先将数据源进行分组,第一重遍历获取所有组,第二重遍历获取某一个组的具体数据public void DataBind() { DateTime time ...

  9. HashMap的key装换成List

    Map<String,Object> map = new HashMap<String,Object>(); map.put("a","32332 ...

随机推荐

  1. Lightoj1059【最小生成树】

    题意: 使得所有的位置都能通向一个机场,问最小花费. 思路: 最小生成树. 本来还想标记一下没有出现过的点,其实那个数组已经解决了.==. PS:注意路比建造机场还贵?直接造机场得了? if ther ...

  2. 黑马MyBatisday2 MyBatis Dao层实现 接口代理实现&传统实现 动态SQL和SQL抽取 自定义类型处理 分页插件PageHelper

    package com.itheima.mapper; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelp ...

  3. eclipse中windows下的preferences左栏没有tomcat?

    是因为缺少eclipse for tomcat 插件,到http://www.eclipsetotale.com/tomcatPlugin.html此网站下载,我的eclipse版本是4.4版本的,所 ...

  4. Codeforces #564div2 E1(记忆化搜索)

    虽然不是正解但毕竟自己做出来了还是记下来吧- 对每个人分别dfs得到其期望,某两维的组合情况有限所以Hash一下避免了MLE. #include <cstdio> #include < ...

  5. GYM 101572C(模拟)

    要点 题意是:以颜色red举例,逆时针找最近的,顺时针找最近的,相减得到val:对三种颜色都做这事然后求和,卖掉最小的,更新,继续. 360度很小所以就像365天一样可以暴力前后扫.每次更新最多6个所 ...

  6. java中读取配置文件内容,如读取.properties文件

    http://blog.csdn.net/u012255097/article/details/53122760

  7. GUI的最终选择 Tkinter(九):事件

    Tkinter事件处理 Tkinter应用会花费大部分的时间在处理事件循环中(通过mainloop()方法进入),事件可以是触发的鼠标,键盘的操作,管理窗口触发的重绘事件(在多数情况下都是有用户间接引 ...

  8. 自定义view(14)使用Path绘制复杂图形

    灵活使用 Path ,可以画出复杂图形,就像美术生在画板上画复杂图形一样.程序员也可以用代码实现. 1.样板图片 这个是个温度计,它是静态的,温度值是动态变化的,所以要自定义个view.动态显示值,温 ...

  9. 通过sqlserver sa密码修改windows操作系统密码

    如果你不记得windows管理员的密码了,但知道sqlserver sa用户的密码,可以通过以下方式修改: 进入SQL之后执行以下语句: -- 允许配置高级选项  EXEC sp_configure ...

  10. fleet-运行一个全局的单元

    运行一个全局的单元 正如前面所提到的,全局单元是有用的,用于在您的集群中的所有机器上运行一个单元.它不会比一个普通的单元差太多,而是一个新的x-fleet参数称为Global=true.这是一个示例单 ...