目錄
- WPF繪圖
- 直線(Line)
- 矩形(Rectangle)
- 橢圓(Ellipse)
- 路徑(Path)
- 路徑標記語法
- 使用Path剪裁界面元素
- 圖形的效果與濾鏡
- 簡單易用的BitmapEffect
- 豐富多彩的Effect
- 圖形的變形
- 呈現變形
- 布局變形
- 影片
- 簡單獨立影片
- 簡單線性影片
- 高級影片控制
- 關鍵幀影片
- 特殊的關鍵幀
- 路徑影片
- 場景
- 簡單獨立影片
WPF在影片和3D上的優勢主要有:
- XAML語言針對的是界面美化問題,可以讓設計師直接加入開發團隊、降低溝通成本,
- XAML的圖形繪制功能非常強大,可以輕易繪制出復雜的圖示、圖畫,
- WPF支持“濾鏡”功能,可以像Photoshop那樣為物件添加各種效果,
- WPF原生支持動面開發,設計師、程式員都能夠使用XAML或C#輕松開發制作出炫麗的影片效果,
- WWF原生支持3D效果,甚至可以將其他3D建模工具創建的模型匯入進來使用,
- Blend作為專門的設計工具讓WPF如虎添翼,既能幫助不了解編程的設計師快速上手,又能幫助資深開發者快速建立圖形或影片的原型,
WPF繪圖
XAML繪圖本身就是矢量的,支持各式各樣的填充和效果,還可以添加濾鏡,
XAML矢量圖是借助Microsoft Expression Studio中的Design和Blend兩個工具畫出來的,Blend可以直接繪制XAML圖形;Design可以像Photoshop或者Fireworks那樣繪制圖形,再由設計者決定匯出為PNG或XAML格式,
這些圖片都是由有限的幾個基本圖形組成的,WPF的基本圖形包括以下幾個(它們都是Shape類的派生類):
- Line:直線段,可以設定其筆觸(Stroke),
- Rectangle:矩形,既有筆觸,又有填充(Fill),
- Ellipse:橢圓,長、寬相等的橢圓即為正圓,既有筆觸又有填充,
- Polygon:多邊形,由多條直線段圍成的閉合區域,既有筆觸又有填充,
- Polyline:折線(不閉合),由多條首尾相接的直線段組成,
- Path:路徑(閉合區域),基本圖形中功能最強大的一個,可由若干直線、圓弧、貝塞爾曲線組成,
直線(Line)
直線是最簡單的圖形,使用X1、Y1兩個屬性可以設定它的起點坐標,X2、Y2兩個屬性則用來設定其終點坐標,控制起點/終點坐標就可以實作平行、交錯等效果,一些屬性還能控制畫出虛線以及控制線段終點的形狀,
Stroke(筆觸)屬性的資料型別是Brush(畫刷),凡是Brush的派生類均可用于給這個屬性賦值,
WPF提供了多種漸變色畫刷,畫直線也可以畫出漸變效果,下面的例子綜合了這些屬性:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="258.651" Width="296.482">
<Grid>
<Line X1="10" Y1="20" X2="260" Y2="20" Stroke="Red" StrokeThickness="10"/>
<Line X1="10" Y1="40" X2="260" Y2="40" Stroke="Orange" StrokeThickness="6"/>
<Line X1="10" Y1="60" X2="260" Y2="60" Stroke="Green" StrokeThickness="3"/>
<Line X1="10" Y1="80" X2="260" Y2="80" Stroke="Purple" StrokeThickness="2"/>
<Line X1="10" Y1="100" X2="260" Y2="100" Stroke="Black" StrokeThickness="1"/>
<Line X1="10" Y1="120" X2="260" Y2="120" StrokeDashArray="3" Stroke="Black" StrokeThickness="1"/>
<Line X1="10" Y1="140" X2="260" Y2="140" StrokeDashArray="5" Stroke="Black" StrokeThickness="1"/>
<Line X1="10" Y1="160" X2="260" Y2="160" Stroke="Black" StrokeEndLineCap="Flat" StrokeThickness="6"/>
<Line X1="10" Y1="180" X2="260" Y2="180" Stroke="Black" StrokeEndLineCap="Triangle" StrokeThickness="8"/>
<Line X1="10" Y1="200" X2="260" Y2="200" StrokeEndLineCap="Round" StrokeThickness="10">
<Line.Stroke>
<LinearGradientBrush EndPoint="0,0.5" StartPoint="1,0.5">
<GradientStop Color="Blue"/>
<GradientStop Offset="1"/>
</LinearGradientBrush>
</Line.Stroke>
</Line>
</Grid>
</Window>
效果如下:

注:繪圖可以在任何一種布局控制元件中完成,WPF會自動根據容器的不同計算圖形的坐標,常用的繪圖容器是Canvas和Grid,
矩形(Rectangle)
矩形由筆觸(Stroke,即邊線)和填充(Fill)構成,Stroke屬性的設定與Line一樣,Fill屬性的資料型別是Brush,
Brush是個抽象類,只能用Brush派生類的實體為Fill屬性賦值,常用的Brush型別有:
- SolidColorBrush:實心畫刷,在XAML中可以使用顏色名稱字串(如Red、Blue)直接賦值,
- LinearGradientBrush:線性漸變畫刷,色彩沿設定的直線方向、按設定的變化點進行漸變,
- RadialGradientBrush:徑向漸變畫刷,色彩沿半徑的方向、按設定的變化點進行漸變,形成圓形填充,
- ImageBrush:使用圖片(Image)作為填充內容,
- DrawingBrush:使用矢量圖(Vector)和位圖(Bitmap)作為填充內容,
- VisualBrush:每個控制元件的可視化形象可以通過Visual類的方法獲得(Visual->FrameworkElement),獲得可視化的形象后可以用VisualBrush這個形象進行填充,如拖拽控制元件時滑鼠松開前的控制元件“幻影”,
下面是使用各種畫刷填充矩形的綜合實體:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="394.452" Width="597.761">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="160"/>
<RowDefinition Height="10"/>
<RowDefinition Height="160"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="180"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="180"/>
</Grid.ColumnDefinitions>
<!--實心填充-->
<Rectangle Grid.Column="0" Grid.Row="0" Stroke="Black" Fill="LightBlue"/>
<!--線性漸變-->
<Rectangle Grid.Column="2" Grid.Row="0">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="#FFB6F8F1" Offset="0"/>
<GradientStop Color="#FF0082BD" Offset="0.25"/>
<GradientStop Color="#FF95DEFF" Offset="0.6"/>
<GradientStop Color="#FF004F72" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<!--徑向漸變-->
<Rectangle Grid.Column="4" Grid.Row="0">
<Rectangle.Fill>
<RadialGradientBrush>
<GradientStop Color="#FFB6F8F1" Offset="0"/>
<GradientStop Color="#FF0082BD" Offset="0.25"/>
<GradientStop Color="#FF95DEFF" Offset="0.75"/>
<GradientStop Color="#FF004F72" Offset="1.5"/>
</RadialGradientBrush>
</Rectangle.Fill>
</Rectangle>
<!--圖片填充-->
<Rectangle Grid.Column="0" Grid.Row="2">
<Rectangle.Fill>
<ImageBrush ImageSource="Resource\Logos\Lamborghini.png" Viewport="0,0,0.3,0.15" TileMode="Tile"/>
</Rectangle.Fill>
</Rectangle>
<!--矢量圖填充-->
<Rectangle Grid.Column="2" Grid.Row="2">
<Rectangle.Fill>
<DrawingBrush Viewport="0,0,0.2,0.2" TileMode="Tile">
<DrawingBrush.Drawing>
<GeometryDrawing Brush="LightBlue">
<GeometryDrawing.Geometry>
<EllipseGeometry RadiusX="10" RadiusY="10"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
</Rectangle.Fill>
</Rectangle>
<!--無填充,用線性漸變填充邊線-->
<Rectangle Grid.Column="4" Grid.Row="2" StrokeThickness="10">
<Rectangle.Stroke>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="White" Offset="0.3"/>
<GradientStop Color="Blue" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Stroke>
</Rectangle>
</Grid>
</Window>
效果如下:

在使用畫刷的時候,建議先在Blend里繪制出大致效果然后再在Visual Studio里進行微調,
接下來看一個VisualBrush的例子,目標控制元件是一個Button,程式的XAML代碼如下:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="394.452" Width="597.761">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="160"/>
</Grid.ColumnDefinitions>
<StackPanel x:Name="stackPanelLeft" Background="White"/>
<Button x:Name="realButton" Content="OK" Height="40"/>
<Button Content=">>>" Grid.Column="1" Margin="5,0" Click="CloneVisual"/>
<StackPanel x:Name="stackPanelRight" Background="White" Grid.Column="2"/>
</Grid>
</Window>
中間Button的Click事件處理器代碼如下:
double o = 1.0;//不透明度計數器
private void CloneVisual(object sender, RoutedEventArgs e)
{
VisualBrush vBrush = new VisualBrush(this.realButton);
Rectangle rect = new Rectangle();
rect.Width = realButton.ActualWidth;
rect.Height = realButton.ActualHeight;
rect.Fill = vBrush;
rect.Opacity = o;
o -= 0.2;
this.stackPanelRight.Children.Add(rect);
}
效果如下:

橢圓(Ellipse)
橢圓也是一種常用的幾何圖形,使用方法與矩形沒有什么區別,
繪制一個球體,球體的輪廓是正圓(Circle),Width與Height相等的橢圓即是正圓;球體的光影效果使用徑向漸變實作,XAML代碼如下:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="394.452" Width="597.761">
<Grid>
<Ellipse Stroke="Gray" Width="140" Height="140" Cursor="Hand" ToolTip="A Ball">
<Ellipse.Fill>
<RadialGradientBrush GradientOrigin="0.2,0.8" RadiusX="0.75" RadiusY="0.75">
<RadialGradientBrush.RelativeTransform>
<TransformGroup>
<RotateTransform Angle="90" CenterX="0.5" CenterY="0.5"/>
<TranslateTransform/>
</TransformGroup>
</RadialGradientBrush.RelativeTransform>
<GradientStop Color="#FFFFFFFF" Offset="0"/>
<GradientStop Color="#FF444444" Offset="0.66"/>
<GradientStop Color="#FF999999" Offset="1"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
</Grid>
</Window>
效果如下:

橢圓的繪制和色彩填充都是在Blend里完成的,在Visual Studio里又進行了一些調整(包括規整數值、調整順序和去掉無用代碼),
路徑(Path)
路徑(Path)完全可以替代其他幾種圖形,可以將直線、圓弧、貝塞爾曲線等基本元素結合進來,形成更復雜的圖形,
路徑最重要的一個屬性是Data,Data的資料型別是Geometry(幾何圖形),使用這個屬性將一些基本的線段拼接起來、形成復雜的圖形,賦值的語法有兩種:
- 標簽式的標準語法
- 專門用于繪制幾何圖形的“路徑標記語法”
本小節借助標準語法認識各種基本線段,下一小節將學習繪制幾何圖形的路徑標記語法,
Path的Data屬性是Geometry類(抽象類,不可直接使用),可以使用的是Geometry的子類,Geometry的子類包括:
- LineGeometry:直線幾何圖形,
- RectangleGeometry:矩形幾何圖形,
- EllipseGeometry:橢圓幾何圖形,
- PathGeometry:路徑幾何圖形,
- StreamGeometry:PathGeometry的輕量級替代品,不支持Binding、影片等功能,
- CombinedGeometry:由多個基本幾何圖形聯合在一起,形成的單一幾何圖形,
- GeometryGroup:由多個基本幾何圖形組合在一起,形成的幾何圖形組,
區別在于前面介紹的Line、Rectangle、Ellipse類都是可以獨立存在的物件,這些*Geometry類只能用于結合成其他幾何圖形、不能獨立存在,
當在Blend里選中一組獨立的幾何圖形并在選單里執行組合路徑的命令時,本質上就是把原來獨立的Line、Rectangle、Ellipse物件轉換成*Geometry物件并結合成一個新的復雜幾何圖形,
下面例子是簡要展示各個幾何圖形:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="340">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="160"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="160"/>
<RowDefinition Height="160"/>
</Grid.RowDefinitions>
<!--直線-->
<Path Stroke="Blue" StrokeThickness="2" Grid.Column="0" Grid.Row="0">
<Path.Data>
<LineGeometry StartPoint="20,20" EndPoint="140,140"/>
</Path.Data>
</Path>
<!--矩形路徑-->
<Path Stroke="Orange" Fill="Yellow" Grid.Column="1" Grid.Row="0">
<Path.Data>
<RectangleGeometry Rect="20,20,120,120" RadiusX="10" RadiusY="10"/>
</Path.Data>
</Path>
<!--橢圓路徑-->
<Path Stroke="Green" Fill="LawnGreen" Grid.Column="0" Grid.Row="1">
<Path.Data>
<EllipseGeometry Center="80,80" RadiusX="60" RadiusY="40"/>
</Path.Data>
</Path>
<!--自定義路徑(最為重要)-->
<Path Stroke="Yellow" Fill="Orange" Grid.Column="1" Grid.Row="1">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure StartPoint="25,140" IsClosed="True">
<PathFigure.Segments>
<LineSegment Point="20,40"/>
<LineSegment Point="40,110"/>
<LineSegment Point="50,20"/>
<LineSegment Point="80,110"/>
<LineSegment Point="110,20"/>
<LineSegment Point="120,110"/>
<LineSegment Point="140,40"/>
<LineSegment Point="135,140"/>
</PathFigure.Segments>
</PathFigure>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
</Grid>
</Window>
效果如下:

WPF繪圖的重點在于Path,Path的重點在于PathGeometry,PathGeometry的Figures屬性可以容納PathFigure物件,而PathFigure的Segments屬性又可以容納各種線段用于結合成復雜圖形,XAML代碼結構如下:
<Path>
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure>
<PathFigure.Segments>
<!--各種線段-->
</PathFigure.Segments>
</PathFigure>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
Figures是PathGeometry的默認內容屬性、Segments是PathFigure的默認內容屬性,常簡化為這樣:
<Path>
<Path.Data>
<PathGeometry>
<PathFigure>
<!--各種線段-->
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
上面格式中的各種線段是:
- LineSegment:直線段,
- ArcSegment:圓弧線段,
- BezierSegment:三次方貝塞爾曲線段(默認貝塞爾曲線就是指三次曲線,所以Cubic一詞被省略),
- QuadraticBezierSegment:二次方貝塞爾曲線段,
- PolyLineSegment:多直線段,
- PolyBezierSegment:多三次方貝塞爾曲線段,
- PolyQuadraticBezierSegment:多二次方貝塞爾曲線,
注:所有這些線段都沒有起點(StartPoint),起點就是前一個線段的終點,而第一個線段的起點則是PathFigure的StartPoint,
LineSegment最為簡單,只需要控制它的Point(終點)即可,XAML代碼如下:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="340">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Path Stroke="Green" Fill="LawnGreen" StrokeThickness="2">
<Path.Data>
<PathGeometry>
<PathFigure IsClosed="True" StartPoint="0,0">
<LineSegment Point="150,0"/>
<LineSegment Point="150,30"/>
<LineSegment Point="90,30"/>
<LineSegment Point="90,150"/>
<LineSegment Point="60,150"/>
<LineSegment Point="60,30"/>
<LineSegment Point="0,30"/>
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
</Grid>
</Window>
效果如下:

ArcSegment用來繪制圓弧:
- Point屬性用來指明圓弧連接的終點;
- Size屬性是完整橢圓的橫軸半徑和縱軸半徑(圓弧截取自橢圓);
- SweepDirection屬性指明圓弧是順時針方向還是逆時針方向;
- IsLargeArc屬性用于指明是否使用大弧去連接(如果橢圓上的兩點位置不對稱,那么這兩點間的圓弧就會分為大弧和小弧);
- RotationAngle屬性用來指明圓弧母橢圓的旋轉角度,
幾個屬性的變化如下所示:

BezierSegment(三次方貝塞爾曲線)由4個點決定:
- 起點:即前一個線段的終點或PathFigure的StartPoint,
- 終點:Point3屬性,即曲線的終點位置,
- 兩個控制點:Point1和Point2屬性,
三次方貝塞爾曲線就是由起點出發走向Pointl的方向,再走向Point2的方向,最后到達終點的平滑曲線,如下為XAML代碼表示的三次方貝塞爾曲線:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="340">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Path Stroke="Black" StrokeThickness="2">
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="0,0">
<BezierSegment Point1="250,0" Point2="50,200" Point3="300,200"/>
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
</Grid>
</Window>
效果如下:

想繪制出復雜的圖畫來,要做的僅僅是在PathFigure把Segment一段一段加上去,
GeometryGroup也是Geometry的一個派生類,它最大的特點是可以將一組PathGeometry組合在一起,如下面的例子所示:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="340">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Path Stroke="Black" Fill="LightBlue" StrokeThickness="1">
<Path.Data>
<GeometryGroup>
<PathGeometry>
<PathFigure StartPoint="0,0">
<BezierSegment Point1="250,0" Point2="50,200" Point3="300,200"/>
</PathFigure>
</PathGeometry>
<PathGeometry>
<PathFigure StartPoint="0,0">
<BezierSegment Point1="230,0" Point2="50,200" Point3="300,200"/>
</PathFigure>
</PathGeometry>
<PathGeometry>
<PathFigure StartPoint="0,0">
<BezierSegment Point1="210,0" Point2="50,200" Point3="300,200"/>
</PathFigure>
</PathGeometry>
<PathGeometry>
<PathFigure StartPoint="0,0">
<BezierSegment Point1="190,0" Point2="50,200" Point3="300,200"/>
</PathFigure>
</PathGeometry>
<PathGeometry>
<PathFigure StartPoint="0,0">
<BezierSegment Point1="170,0" Point2="50,200" Point3="300,200"/>
</PathFigure>
</PathGeometry>
<PathGeometry>
<PathFigure StartPoint="0,0">
<BezierSegment Point1="150,0" Point2="50,200" Point3="300,200"/>
</PathFigure>
</PathGeometry>
<PathGeometry>
<PathFigure StartPoint="0,0">
<BezierSegment Point1="130,0" Point2="50,200" Point3="300,200"/>
</PathFigure>
</PathGeometry>
</GeometryGroup>
</Path.Data>
</Path>
</Grid>
</Window>
效果如下:

路徑標記語法
Path的一大缺點是其標簽式語法的煩瑣,復雜圖形(Path)都是由數十條線段連接而成,按照標簽式語法,每條線段(Segment)是一個標簽、每個標簽占據一行,一個圖形就要占去幾十行代碼,
借助專供WPF繪圖使用的路徑標記語法(Path Markup Syntax)可以極大地簡化Path的描述,路徑標記語法實際上就是各種線段的簡記法(
使用路徑標記語法繪圖時一般分三步:移動至起點一繪圖→閉合圖形,這三步使用的命令稍有差別:
- 移動到起點使用的是“移動命令”M;
- 繪圖使用的是繪圖命令,包括L、H、V、A、C、Q等;
- 如果圖形是閉合的,需要使用“閉合命令”Z,這樣最后一條線段的終點與第一條線段的起點間會連接上一條直線段,
路徑標記語法不區分大小寫(A與a、H與h等價),使用兩個double型別數值來表示一個點,第一個值表示橫坐標(常記為x),第二個值表示縱坐標(常記為y),兩個數值既可以使用逗號分隔(x,y)又可以使用空格分隔(x y),
注:由于路徑標記法語中使用空格作為兩個點之間的分隔,為了避免混淆,建議使用逗號作為點橫縱坐標的分隔符,
常用路徑標記語法的總結如下所示:


在上述命令中,S和T兩個命令比較特殊:
- S用于繪制平滑三次方貝塞爾曲線,只需要給出一個控制點(相當于普通三次方貝塞爾曲線的第二個控制點),平滑三次方貝塞爾曲線會把前一條三次方貝塞爾曲線的第二控制點以起點為對稱中心的對稱點當作自己的第一控制點(如果前面的線段不是三次方貝塞爾曲線,則第一控制點與起點相同),
下面兩條曲線等價:
<Path Stroke="Red" Data="https://www.cnblogs.com/timefiles/archive/2021/03/30/M 0,0 C30,0 70,100 100,100 S 170,0 200,0"/>
<Path Stroke="Black" Data="https://www.cnblogs.com/timefiles/archive/2021/03/30/M 0,0 C30,0 70,100 100,100 C 130,100 170,0 200,0"/>
- T命令用于繪制平滑二次方貝塞爾曲線,繪制的時候如果前面的線段也是一段二次方貝塞爾曲線的話,T命令會把前面這段曲線的控制點以起點為對稱中心的對稱點當作自己的控制點(如果前面的線段不是二次方貝塞爾曲線則控制點與起點相同),
下面兩條曲線等價:
<Path Stroke="Red" Data="https://www.cnblogs.com/timefiles/archive/2021/03/30/M 0,200 Q 100,0 200,200 T 400,200"/>
<Path Stroke="Black" Data="https://www.cnblogs.com/timefiles/archive/2021/03/30/M 0,200 Q 100,0 200,200 Q 300,400 400,200"/>
使用方法是把這些命令串起來、形成一個字串,然后賦值給Path的Data屬性,使用Blend繪圖時,Blend會自動使用路徑標記語法來記錄資料而不是使用代碼量巨大的標簽式語法,
使用Path剪裁界面元素
遇到制作不規則表單或控制元件的需求,僅需使用表單或控制元件的Clip屬性就可以輕松做到,Clip屬性被定義在UIElement類中,WPF表單和所有控制元件、圖形都具有這個屬性,
Clip屬性的資料型別是Geometry(與Path的Data屬性一致),只要按需求制作好特殊形狀的Path并把Path的Data屬性值賦給目標表單、控制元件或其他圖形,對目標的剪切就完成了,
請看下面這個不規則表單的例子(資料經過優化):
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="340" AllowsTransparency="True" WindowStyle="None">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Path Visibility="Hidden" x:Name="clipPath" Data="https://www.cnblogs.com/timefiles/archive/2021/03/30/M 55,100 A 50,50 0 1 1 100,60 A 110,95 0 0 1 200,60 A 50,50 0 1 1 250,100 A 110,95 0 1 1 55,100 Z"/>
<Button VerticalAlignment="Center" HorizontalAlignment="Center" Width="80" Height="25" Name="butonClip" Click="buttonClip_Click">Clip</Button>
</Grid>
</Window>
注:想讓一個表單能夠被剪切,其AllowsTransparency必須設為True,WindowStyle屬性必須設為None,
表單中Buton的Click事件處理器如下:
private void buttonClip_Click(object sender, RoutedEventArgs e)
{
this.Clip = this.clipPath.Data;
}
效果如下:

圖形的效果與濾鏡
在UIElement類的成員中可以找到BitmapEffect和Effect這兩個屬性,這兩個屬性都能用來為UI元素增加效果,BitmapEffect屬性(已過時)使用CPU的運算能力為UI元素添加效果,Effect屬性使用GPU的運算能力為UI元素添加效果,
簡單易用的BitmapEffect
BitmapEffect屬性定義在UIEemet類中,它的資料型別是BitmapEffect類(抽象類),只能用BitmapEffect類的派生類實體為UIElement的BitmapEffect屬性賦值,
BitmapEffect類的派生類包括如下幾個:
- BevelBitmapEffect:斜角效果,
- BitmapEffectGroup:復合效果(可以把多個BitmapEffect組合在一起),
- BlurBitmapEffect:模糊效果,
- DropShadowBitmapEffec:投影效果,
- EmbossBitmapEffect:浮雕效果,
- OuterGlowBitmapEffect:外發光效果,
每個效果都有自己的一系列屬性可以調整,下面是一個DropShadowBitmapEffect的簡單例子:
<Grid>
<Button Content="Click Me" Grid.Column="0" Grid.Row="0" Margin="20">
<Button.BitmapEffect>
<DropShadowBitmapEffect Direction="-45" Opacity="0.75" ShadowDepth="7"/>
</Button.BitmapEffect>
</Button>
</Grid>
效果如下:

豐富多彩的Effect
在繪圖軟體Photoshop中,使用濾鏡插件能獲得如下好處:
- 提高作業效率,
- 得到更專業的效果,
- 對使用者的技術水平要求相對較低,
WPF引進了這種“濾鏡插件”的思想——UIElement類的Effect屬性,Effect屬性的資料型別是Effect類(抽象類),可以接收Effect類的任何一個派生類的派生類實體作為它的值,
Effect類位于System.Windows.Media.Effects名稱空間中,它的派生類有3個,分別是:
- BlurEffect:模糊效果,
- DropShadowEffect:投影效果,
- ShaderEffect:著色器效果(抽象類),
模糊和投影效果在編程中用的最多,.NET Framework內建了這兩個效果,使用起來非常方便(用GPU進行渲染),ShaderEffect(抽象類)是留給濾鏡插件開發人員的介面,只要是派生自ShaderEffec的效果類就可以直接拿來用,
開發著色器效果需要使用Pixel Shader 語言(簡寫與Photoshop一樣,也是PS)和一些DirectX的知識,大多數WPF開發人員需要的是現成的效果濾鏡,可以使用官方的濾鏡包,參考一些WPF中的濾鏡特效——Effect Library
圖形的變形
WPF中的“變形”一詞含義很廣,尺寸、位置、坐標系比例、旋轉角度等的變化都算是變形,
WPF中的變形與UI元素是分開的,如設計一個“向左旋轉45度”的變形賦值給不同UI元素的變形控制屬性,這些UI元素就都向左旋轉45度了,
控制變形的屬性有兩個,分別是:
- RenderTransform:呈現變形,定義在UIElement類中,
- LayoutTransform:布局變形,定義在FrameworkElement類中,
FrameworkElement派生自UIElement,而控制元件的基類Control類又派生自FrameworkElement,所以在控制元件級別兩個屬性都能看到,
這兩個屬性都是依賴屬性,它們的資料型別都是Transform抽象類,Transform類的派生類實均可用來為這兩個屬性賦值,
Transform抽象類的派生類有如下一些:
- MatrixTransform:矩陣變形,把容納被變形UI元素的矩形頂點看作一個矩陣進行變形,
- Rotate Transform:旋轉變形,以給定的點為旋轉中心,以角度為單位進行旋轉變形,
- ScaleTransform:坐標系變形,調整被變形元素的坐標系,可產生縮放效果,
- SkewTransform:拉伸變形,可在橫向和縱向上對被變形元素進行拉伸,
- TranslateTransform:偏移變形,使被變形元素在橫向或縱向上偏移一個給定的值,
- TransformGroup:變形組,可以把多個獨立變形合成為一個變形組、產生復合變形效果,
呈現變形
WPF的RenderTransform屬性就是起到“呈現變形(Render Transform)”作用,讓UI元素呈現出來的屬性與它本來的屬性不一樣,
一個按鈕本來處在Canvas或者Grid的左上角,可以使用RenderTransform屬性讓其呈現在右下角并且向右旋轉45°,XAML代碼如下:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="351" Width="420">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Width="80" HorizontalAlignment="Left" VerticalAlignment="Top" Height="80" Content="Hello">
<Button.RenderTransform>
<!--復合變形-->
<TransformGroup>
<RotateTransform CenterX="40" CenterY="40" Angle="45"/>
<TranslateTransform X="300" Y="200"/>
</TransformGroup>
</Button.RenderTransform>
</Button>
</Grid>
</Window>
Grid的第一行的行高、第一列的列寬都由Button來決定,在表單設計器里可以清晰地看到Button本身的位置并沒有改變(第一行和第一列沒有變化),但Button卻出現在了右下(300,200)的位置,并向右旋轉了45°,
效果如下:

用戶并不能察覺到究竟是控制元件本身的位置、角度發生了改變,還是呈現的位置與角度發生了改變,
在表單上移動UI元素本身會導致表單布局的改變,而表單布局的每一個(哪怕是細微的)變化都將導致所有表單元素的尺寸測算函式、位置測算函式、呈現函式等的呼叫,造成系統資源占用激增、程式性能陡降,
使用呈現變形則不會遇到這樣的問題,呈現變形只改變元素“出現在哪里”,不牽扯布局的改變、只涉及表單的重繪,制作影片時切記要使用RenderTransform,
布局變形
與呈現變形不同,布局變形會影響表單的布局、導致表單布局的重新測算,因為表單布局的重新測算和繪制會影響程式的性能,所以布局變形一般只用在靜態變形上,而不用于制作影片,
考慮這樣一個需求:制作一個文字縱向排列的淺藍色標題欄,如果我們使用呈現變形,代碼如下:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="351" Width="420">
<Grid>
<!--Layout-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--Content-->
<Grid x:Name="titleBar" Background="LightBlue">
<TextBlock Text="Hello Transformer!" FontSize="24" HorizontalAlignment="Left" VerticalAlignment="Bottom">
<TextBlock.RenderTransform>
<RotateTransform Angle="-90"/>
</TextBlock.RenderTransform>
</TextBlock>
</Grid>
</Grid>
</Window>
效果如下:

TextBox本身并沒有改變,改變的只是它的顯示,它的真實寬度仍然把寬度設為Auto的第一列撐得很寬,
分析需求,實際上需要的是靜態改變TextBox的布局,因此應該使用LayoutTransform,對上面的代碼做一處改動:
<TextBlock.LayoutTransform>
<RotateTransform Angle="-90"/>
</TextBlock.LayoutTransform>
效果如下:

影片
影片本質就是在一個時間段內物件位置、角度、顏色、透明度等屬性值的連續變化,有些是物件自身的屬性,有些則是圖形變形的屬性,
注:WPF規定——可以用來制作影片的屬性必須是依賴屬性,
變化即是運動,WPF的影片也是一種運動:
- 運動的主體就是各種UI元素,
- 運動本身就是施加在UI元素上的一些Timeline派生類的實體,
在實際作業中,往往就是先設計好一個影片構思、用一個Timeline派生類的實體加以表達,最后讓某個UI元素來執行這個影片、完成影片與影片主體的結合,
簡單的影片由一個元素來完成就可以了,WPF把簡單影片稱為AnimationTimeline,
復雜的(即并行的、復合的)影片就需要UI上的多個元素協同完成,包括有哪些UI元素參與影片、每個元素的影片行為是什么、影片何時開始何時結束等,WPF把一組協同的影片也稱為Storyboard,
Timeline、AnimationTimeline和Storyboard的關系如下所示:

簡單獨立影片
影片就是“會動的畫”,“會動”指的就是能夠讓UI元素或元素變形的某個屬性值產生連續變化,
任何一個屬性都有自己的資料型別(如UIElement的Width和Height屬性為Double型別),幾乎針對每個可能的資料型別,WPF的影片子系統都為其準備了相應的影片類(均派生自AnimationTimeline),它們包括:
- BooleanAnimationBase
- ByteAnimationBase
- CharAnimationBase
- ColorAnimationBase
- DecimalAnimationBase
- DoubleAnimationBase
- Int16AnimationBase
- Int32AnimationBase
- Int64AnimationBase
- MatrixAnimationBase
- ObjectAnimationBase
- Point3DAnimationBase
- PointAnimationBase
- QuaternionAnimationBase
- RectAnimationBase
- Rotation3DAnimationBase
- SingleAnimationBase
- SizeAnimationBase
- StringAnimationBase
- ThicknessAnimationBase
- Vector3DAnimationBase
- VectorAnimationBase
上面列出的這些類都是抽象基類(帶有Base后綴),完整的情況下,這些抽象基類又能派生出3種具體影片,即簡單影片、關鍵幀影片、沿路徑運動的影片,
如DoubleAnimationBase完整地派生出了3個具體影片,如下所示:

注:針對于int型別屬性的Imt32AnimationBase只派生出Int32Animation和Int32AnimationUsingKeyFrames兩個具體影片類,BooleanAnimationBase和CharAnimationBase的派生類則更少——只有關鍵幀影片類,
在WPF影片系統中Double型別的屬性用得最多,而且DoubleAnimationBase的派生類也最完整,下面只講述DoubleAnimationBase的派生類,
用戶界面上只包含一個Button,這個Button的RenderTransform屬性值是一個名為tt的TranslateTransform物件,改變這個物件的X和Y值就會讓Buton的顯示位置(而不是真實位置)變化,XAML代碼如下:
<Grid>
<Button Content="Move!" HorizontalAlignment="Left" VerticalAlignment="Top" Width="60" Height="60" Click="Button_Click">
<Button.RenderTransform>
<TranslateTransform x:Name="tt" X="0" Y="0"/>
</Button.RenderTransform>
</Button>
</Grid>

簡單線性影片
“簡單線性影片”是指僅由變化起點、變化終點、變化幅度、變化時間4個要素構成的影片:
- 變化時間(Duration屬性):必須指定,資料型別為Duration,
- 變化終點(To屬性):如果沒有指定變化終點,程式將采用上一次影片的終點或默認值,
- 變化幅度(By屬性):如果同時指定了變化終點,變化幅度將被忽略,
- 變化起點(From屬性):如果沒有指定變化起點則以變化目標屬性的當前值為起點,
每次單擊按鈕,按鈕都會從起始位置(表單的左上角)向表單右下長寬不超出300像素的矩形內的某點運動,完成運動的時長是300毫秒,Button的Click事件處理器代碼如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
//TranslateTransform的X、Y屬性均為Double型別,選用DoubleAnimation來使之產生變化
//宣告dax和daY兩個DoubleAnimation變數并分別為之創建參考實體
DoubleAnimation daX = new DoubleAnimation();
DoubleAnimation daY = new DoubleAnimation();
//指定起點
daX.From = 0D;
daY.From = 0D;
//指定終點
Random r = new Random();
daX.To = r.NextDouble() * 300;
daY.To = r.NextDouble() * 300;
//指定時長
Duration duration = new Duration(TimeSpan.FromMilliseconds(300));
daX.Duration = duration;
daY.Duration = duration;
// 影片的主體是TranslateTransform 變形,而非Button
//呼叫BeginAnimation方法,讓daX、daY分別作用在TranslateTransform的XProperty、YProperty依賴屬性上
this.tt.BeginAnimation(TranslateTransform.XProperty, daX);
this.tt.BeginAnimation(TranslateTransform.YProperty, daY);
}
以下幾處值得注意:
- 想讓按鈕從當前位置開始下一次影片,只需要把“daX.From=0D;”和“daY.From=0D;”兩句代碼移除即可,
- 盡管表現出來的是Button在移動,但DoubleAnimation的作用目標并不是Button而是TranslateTransform實體,
- 用來制作影片的屬性必須是依賴屬性,TranslateTransform的XProperty和YProperty就是兩個依賴屬性,
- UIElement和Animatable兩個類都定義有BeginAnimation方法,方法的呼叫者就是影片要作用的目標物件,兩個引數分別指明被作用的依賴屬性和設計好的影片,
每次單擊按扭,按鈕都向表單的右下角移動,則把事件處理器的代碼改變成這樣:
private void Button_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation daX = new DoubleAnimation();
DoubleAnimation daY = new DoubleAnimation();
//指定幅度
daX.By = 100D;
daY.By = 100D;
//指定時長
Duration duration = new Duration(TimeSpan.FromMilliseconds(300));
daX.Duration = duration;
daY.Duration = duration;
// 影片的主體是TranslateTransform 變形,而非Button
this.tt.BeginAnimation(TranslateTransform.XProperty, daX);
this.tt.BeginAnimation(TranslateTransform.YProperty, daY);
}
高級影片控制
使用From、To、By、Duration幾個屬性進行組合就已經可以制作很多不同效果的影片了,如果想制作更加復雜或逼真的影片,還需要使用以下一些效果:


在這些屬性中,EasingFunction是一個擴展性非常強的屬性,取值是IEasingFunction介面型別,自帶的派生類有十多種,
比如BounceEase可以產生乒乓球彈跳式的效果,把前面例子的代碼改成這樣:
private void Button_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation daX = new DoubleAnimation();
DoubleAnimation daY = new DoubleAnimation();
//設定反彈
BounceEase be = new BounceEase();
be.Bounces = 3; // 彈跳3次
be.Bounciness = 3; //彈性程度,值越大反彈越低
daY.EasingFunction = be;
//指定終點
daX.To = 300;
daY.To = 300;
//指定時長
Duration duration = new Duration(TimeSpan.FromMilliseconds(2000));
daX.Duration = duration;
daY.Duration = duration;
// 影片的主體是TranslateTransform 變形,而非Button
this.tt.BeginAnimation(TranslateTransform.XProperty, daX);
this.tt.BeginAnimation(TranslateTransform.YProperty, daY);
}
關鍵幀影片
影片是UI元素屬性連續改變所產生的視覺效果,屬性每次細微的變化都會產生一個新的畫面,每個新畫面就稱為一“幀”,幀的連續播放就產生影片效果,單位時間內播放的幀數越多,影片的效果就越細致,
簡單影片只設定了起點和終點,之間的影片幀都是由程式計算出來并繪制的,程式員無法進行控制,
關鍵幀影片則允許程式員為一段影片設定幾個“里程碑”,影片執行到里程碑所在的時間點時,被影片所控制的屬性值也必須達到設定的值,這些時間線上的“里程碑”就是關鍵幀,
讓Button在單擊后用900毫秒的時長從左上角移動到右下角,但移動路線不是直接移動而是走“Z”字形,Button的Click事件處理器代碼如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
//創建兩個DoubleAnimationUsingKeyFrames實體
//一個控制TranslateTransform的X屬性,另一個控制Translate Transform的Y屬性
//每個DoubleAnimationUsingKeyFrames各擁有三個關鍵幀用于指明X或Y在三個時間點(兩個拐點和終點)應該達到什么樣的值
DoubleAnimationUsingKeyFrames dakX = new DoubleAnimationUsingKeyFrames();
DoubleAnimationUsingKeyFrames dakY = new DoubleAnimationUsingKeyFrames();
// 設定影片總時長
dakX.Duration = new Duration(TimeSpan.FromMilliseconds(900));
dakY.Duration = new Duration(TimeSpan.FromMilliseconds(900));
//創建、添加關鍵幀
LinearDoubleKeyFrame x_kf_1 = new LinearDoubleKeyFrame();
LinearDoubleKeyFrame x_kf_2 = new LinearDoubleKeyFrame();
LinearDoubleKeyFrame x_kf_3 = new LinearDoubleKeyFrame();
x_kf_1.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(300));
x_kf_1.Value = https://www.cnblogs.com/timefiles/archive/2021/03/30/200;
x_kf_2.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(600));
x_kf_2.Value = 0;
x_kf_3.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(900));
x_kf_3.Value = 200;
dakX.KeyFrames.Add(x_kf_1);
dakX.KeyFrames.Add(x_kf_2);
dakX.KeyFrames.Add(x_kf_3);
LinearDoubleKeyFrame y_kf_1 = new LinearDoubleKeyFrame();
LinearDoubleKeyFrame y_kf_2 = new LinearDoubleKeyFrame();
LinearDoubleKeyFrame y_kf_3 = new LinearDoubleKeyFrame();
y_kf_1.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(300));
y_kf_1.Value = 0;
y_kf_2.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(600));
y_kf_2.Value = 180;
y_kf_3.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(900));
y_kf_3.Value = 180;
dakY.KeyFrames.Add(y_kf_1);
dakY.KeyFrames.Add(y_kf_2);
dakY.KeyFrames.Add(y_kf_3);
//執行影片
this.tt.BeginAnimation(TranslateTransform.XProperty, dakX);
this.tt.BeginAnimation(TranslateTransform.YProperty, dakY);
}
在這組關鍵幀影片中,使用的是最簡單的關鍵幀LinearDoubleKeyFrame,這種關鍵幀的特點就是只需你給定時間點(KeyTime屬性)和到達時間點時目標屬性的值(Value屬性)影片就會讓目標屬性值在兩個關鍵幀之間勻速變化,
上面的代碼中,為關鍵幀的KeyTime屬性使用了KeyTime.FromTimeSpan靜態方法,這樣可以得到一個絕對時間點,使用KeyTime.FromPercent靜態方法則可以獲得以百分比計算的相對時間點,程式將整個關鍵幀影片的時長(Duration)視為100%,
無論把dakX的Duration改為多少,三個關鍵幀都會將整個影片分割為均等的三段,代碼改動如下:
//...
x_kf_1.KeyTime = KeyTime.FromPercent(0.33);
x_kf_1.Value = https://www.cnblogs.com/timefiles/archive/2021/03/30/200;
x_kf_2.KeyTime = KeyTime.FromPercent(0.66);
x_kf_2.Value = 0;
x_kf_3.KeyTime = KeyTime.FromPercent(1);
x_kf_3.Value = 200;
//...
特殊的關鍵幀
DoubleAnimationUsingKeyFrames的KeyFrames屬性的資料型別是DoubleKeyFrameCollection,此集合類可接收的元素型別為DoubleKeyFrame,
DoubleKeyFrame是一個抽象類,前面使用的LinearDoubleKeyFrame就是它的派生類之一,DoubleKeyFrame的所有派生類如下:
- LinearDoubleKeyFrame:線性變化關鍵幀,目標屬性值的變化是直線性的、均勻的,即變化速率不變,
- DiscreteDoubleKeyFrame:不連續變化關鍵幀,目標屬性值的變化是跳躍性的、躍遷的,
- SplineDoubleKeyFrame:樣條函式式變化關鍵幀,目標屬性值的變化速率是一條貝塞爾曲線,
- EasingDoubleKeyFrame:緩沖式變化關鍵幀,目標屬性值以某種緩沖形式變化,
4個派生類中最常用的是SplineDoubleKeyFrame(SplineDoubleKeyFrame可以替代LinearDoubleKeyFrame),使用SplineDoubleKeyFrame可以非常方便地制作非勻速影片,因為它使用一條貝塞爾曲線來控制目標屬性值的變化速率,
這條用于控制變化速率的貝塞爾曲線的起點是(0,0)和(1,1),分別映射著目標屬性的變化起點和變化終點,意思是目標屬性值由0%變化到100%,
這條貝塞爾曲線有兩個控制點ControlPointl和ControlPoint2,意思是貝塞爾曲線從起點出發先向ControlPoint1的方向前進、再向ControlPoint2的方向前進、最后到達終點,形成一條平滑的曲線,
如果設定ControlPoint1和ControlPoint2的橫縱坐標值相等,比如(0,0)、(0.5,0.5)、(1,1),則貝塞爾曲線成為一條直線,這時候SplineDoubleKeyFrame與LinearDoubleKeyFrame是等價的,
關鍵幀影片控制Button的位置變形、讓Button橫向移動,整個影片只有一個關鍵幀(使用的是SplineDoubleKeyFrame),變化速率控制曲線的兩個控制點分別是(0,1)和(1,0),目標屬性值會以“快一慢一快”的形式變化,Button的Click事件處理器代碼如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
//創建影片
DoubleAnimationUsingKeyFrames dakX = new DoubleAnimationUsingKeyFrames();
dakX.Duration = new Duration(TimeSpan.FromMilliseconds(1000));
// 創建、添加關鍵幀
SplineDoubleKeyFrame kf = new SplineDoubleKeyFrame();
kf.KeyTime = KeyTime.FromPercent(1);
kf.Value = https://www.cnblogs.com/timefiles/archive/2021/03/30/400;
KeySpline ks = new KeySpline();
ks.ControlPoint1 = new Point(0, 1);
ks.ControlPoint2 = new Point(1, 0);
kf.KeySpline = ks;
dakX.KeyFrames.Add(kf);
//執行影片
this.tt.BeginAnimation(TranslateTransform.XProperty, dakX);
}
路徑影片
使用DoubleAnimationUsingPath類,可以讓目標物件沿著一條給定的路徑移動,
DoubleAnimationUsingPath需要一個PathGeometry來指明移動路徑,PathGeometry的資料資訊可以用XAML的Path語法書寫,
PathGeometry的另一個重要屬性是Source,Source屬性的資料型別是PathAnimationSource列舉,列舉值可取X、Y或Angle:
- 取值是PathAnimationSource.X,意味著這個影片關注的是曲線上每一點橫坐標的變化;
- 取值是PathAnimationSource.Y,意味著這個影片關注的是曲線上每一點縱坐標的變化;
- 取值是PathAnimationSource.Angle,意味著這個影片關注的是曲線上每一點處切線方向的變化,
讓Button沿著一條貝塞爾曲線做波浪形運動,程式的XAML代碼如下:
<Grid x:Name="LayoutRoot">
<Grid.Resources>
<!--移動路徑-->
<PathGeometry x:Key="movingPath" Figures="M 0,150 C 300,-100 300,400 600,120"/>
</Grid.Resources>
<Button Content="Move!" HorizontalAlignment="Left" VerticalAlignment="Top" Width="60" Height="60" Click="Button_Click">
<Button.RenderTransform>
<TranslateTransform x:Name="tt" X="0" Y="0"/>
</Button.RenderTransform>
</Button>
</Grid>
Button的Click事件處理器代碼如下(添加自動回傳和回圈控制):
private void Button_Click(object sender, RoutedEventArgs e)
{
//從XAML代碼中獲取移動路徑資料
PathGeometry pg = this.LayoutRoot.FindResource("movingPath") as PathGeometry;
Duration duration = new Duration(TimeSpan.FromMilliseconds(600));
//創建影片
DoubleAnimationUsingPath dapX = new DoubleAnimationUsingPath();
dapX.PathGeometry = pg;
dapX.Source = PathAnimationSource.X;
dapX.Duration = duration;
DoubleAnimationUsingPath dapY = new DoubleAnimationUsingPath();
dapY.PathGeometry = pg;
dapY.Source = PathAnimationSource.Y;
dapY.Duration = duration;
//自動回傳、永遠回圈
dapX.AutoReverse = true;
dapX.RepeatBehavior = RepeatBehavior.Forever;
dapY.AutoReverse = true;
dapY.RepeatBehavior = RepeatBehavior.Forever;
// 執行影片
this.tt.BeginAnimation(TranslateTransform.XProperty, dapX);
this.tt.BeginAnimation(TranslateTransform.YProperty, dapY);
}
場景
場景(Storyboard)就是并行執行的一組影片(前面講述的關鍵幀影片則是串行執行的一組影片),
設計WPF的場景時,可按以下步驟進行:
- 把一組獨立的影片組織在一個Storyboard元素中、安排好它們的協作關系,
- 指定哪個影片由哪個UI元素、哪個屬性負責完成,
- 為Storyboard選擇一個恰當的觸發時機,比如按鈕按下時或下載開始時,
一旦觸發條件被滿足,影片場景就會開始執行,用戶就會看到影片效果,
下面是一個Storyboard的例子,單擊按鈕后三個小球分別在不同的時間開始向右以不同的速度移動,程式的XAML代碼如下:
<Grid Margin="6">
<!--布局控制-->
<Grid.RowDefinitions>
<RowDefinition Height="38"/>
<RowDefinition Height="38"/>
<RowDefinition Height="38"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="60"/>
</Grid.ColumnDefinitions>
<!--跑道(紅)-->
<Border BorderBrush="Gray" BorderThickness="1" Grid.Row="0">
<Ellipse x:Name="ballR" Height="36" Width="36" Fill="Red" HorizontalAlignment="Left">
<Ellipse.RenderTransform>
<TranslateTransform x:Name="ttR"/>
</Ellipse.RenderTransform>
</Ellipse>
</Border>
<!--跑道(綠)-->
<Border BorderBrush="Gray" BorderThickness="1,0,1,1" Grid.Row="1">
<Ellipse x:Name="ballG" Height="36" Width="36" Fill="LawnGreen" HorizontalAlignment="Left">
<Ellipse.RenderTransform>
<TranslateTransform x:Name="ttG"/>
</Ellipse.RenderTransform>
</Ellipse>
</Border>
<!--跑道(藍)-->
<Border BorderBrush="Gray" BorderThickness="1,0,1,1" Grid.Row="2">
<Ellipse x:Name="ballB" Height="36" Width="36" Fill="Blue" HorizontalAlignment="Left">
<Ellipse.RenderTransform>
<TranslateTransform x:Name="ttB"/>
</Ellipse.RenderTransform>
</Ellipse>
</Border>
<!--按鈕-->
<Button Content="Go!" Grid.Column="1" Grid.RowSpan="3" Click="Button_Click"/>
</Grid>
Button的Click事件處理器代碼如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
Duration duration = new Duration(TimeSpan.FromMilliseconds(600));
// 紅色小球勻速移動
DoubleAnimation daRx = new DoubleAnimation();
daRx.Duration = duration;
daRx.To = 400;
//綠色小球變速運動
DoubleAnimationUsingKeyFrames dakGx = new DoubleAnimationUsingKeyFrames();
dakGx.Duration = duration;
SplineDoubleKeyFrame kfG = new SplineDoubleKeyFrame(400, KeyTime.FromPercent(1.0));
kfG.KeySpline = new KeySpline(1, 0, 0, 1);
dakGx.KeyFrames.Add(kfG);
//藍色小球變速運動
DoubleAnimationUsingKeyFrames dakBx = new DoubleAnimationUsingKeyFrames();
dakBx.Duration = duration;
SplineDoubleKeyFrame kfB = new SplineDoubleKeyFrame(400, KeyTime.FromPercent(1.0));
kfB.KeySpline = new KeySpline(0, 1, 1, 0);
dakBx.KeyFrames.Add(kfB);
//創建場景
Storyboard storyboard = new Storyboard();
Storyboard.SetTargetName(daRx, "ttR");
Storyboard.SetTargetProperty(daRx, new PropertyPath(TranslateTransform.XProperty));
Storyboard.SetTargetName(dakGx, "ttG");
Storyboard.SetTargetProperty(dakGx, new PropertyPath(TranslateTransform.XProperty));
Storyboard.SetTargetName(dakBx, "ttB");
Storyboard.SetTargetProperty(dakBx, new PropertyPath(TranslateTransform.XProperty));
storyboard.Duration = duration;
storyboard.Children.Add(daRx);
storyboard.Children.Add(dakGx);
storyboard.Children.Add(dakBx);
storyboard.Completed += (a, b) => { MessageBox.Show(ttR.X.ToString()); };
storyboard.Begin(this);
}
使用C#代碼實作Storyboard非常復雜,除了拿來做研究或遇到非得使用C#動態創建Storyboard的情況,不然都是用XAML代碼創建Storyboard,
Storyboard一般都放在UI元素的Trigger里,Trigger在觸發時會執行
為Buton添加Trigger并去掉對Click事件的訂閱,XAML代碼其他的部分不做任何改動,代碼如下:
<Button Content="Go!" Grid.Column="1" Grid.RowSpan="3">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard Duration="0:0:0.6">
<!--紅色小球影片-->
<DoubleAnimation Duration="0:0:0.6" To="400" Storyboard.TargetName="ttR" Storyboard.TargetProperty="X"/>
<!--綠色小球影片-->
<DoubleAnimationUsingKeyFrames Duration="0:0:0.6" Storyboard.TargetName="ttG" Storyboard.TargetProperty="X">
<SplineDoubleKeyFrame KeyTime="0:0:0.6" Value="https://www.cnblogs.com/timefiles/archive/2021/03/30/400" KeySpline="1,0,0,1"/>
</DoubleAnimationUsingKeyFrames>
<!--紅藍小球影片-->
<DoubleAnimationUsingKeyFrames Duration="0:0:0.6" Storyboard.TargetName="ttB" Storyboard.TargetProperty="X">
<SplineDoubleKeyFrame KeyTime="0:0:0.6" Value="https://www.cnblogs.com/timefiles/archive/2021/03/30/400" KeySpline="0,1,1,0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/270450.html
標籤:.NET技术
