WPF之图像、图形和视觉画刷的使用

图像画刷
  ImageBrush常用于渲染图片,其属性ImageSource由ImageSource类定义而成,用于设置图像信息。但ImageSource是一个抽象类,因此设置图像信息的任务落到了其子类BitmapImage身上。ImageBrush还有另外一个常用属性Stretch用于图片填充模式,默认值为Fill。
ImageBrush在XAML中示例代码如下:


    
        
            
                
            
        
    

C#:

Canvas canvas = new Canvas();
canvas.Height = 200;
canvas.Width = 200;
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri("Picture/帽子.jpg", UriKind.Relative));
canvas.Background = imageBrush;

绘图画刷
  DrawingBrush用途比较多,可以用于绘制形状、文本、图像以及视频。各绘制对象如下:

1、GeometryDrawing:绘制形状
2、ImageDrawing:绘制图像
3、GlyphRunDrawing:绘制文字
4、VideoDrawing:音频和视频的播放
5、DrawingGroup:绘图组,将其它图形合并到单个复合图形

  下面将展示一个按钮,按钮内部有三个连着的站着的椭圆,椭圆的边缘线宽度为2,示例代码如下:
XAML:


C#:

Button btn = new Button();
btn.Height = 50;
btn.Width = 100;
btn.Content = "A Button";
DrawingBrush drawingBrush = new DrawingBrush();
GeometryDrawing geometryDrawing = new GeometryDrawing();
GeometryGroup geometryGroup = new GeometryGroup();
geometryGroup.Children.Add(new EllipseGeometry(new Point(25, 50), 12.5, 25));
geometryGroup.Children.Add(new EllipseGeometry(new Point(50, 50), 12.5, 25));
geometryGroup.Children.Add(new EllipseGeometry(new Point(70, 50), 12.5, 25));
geometryDrawing.Geometry = geometryGroup;
geometryDrawing.Pen = new Pen(new SolidColorBrush(Colors.Gray), 2);
geometryDrawing.Brush = new SolidColorBrush(Colors.AliceBlue);
drawingBrush.Drawing = geometryDrawing;
btn.Background = drawingBrush;

视觉画刷
  视觉画刷在所有画刷中,属于低层次的画刷,因为属性Visual是所有UI元素的祖先,因此VisualBrush可以使用WPF中所有UI元素进行渲染。以下代码将显示StackPanel、Ellipse、TextBlock以及Button组合的渲染效果。
XAML:


    
        
            
                
                    
                    
                    

C#:

Rectangle rectangle = new Rectangle();
rectangle.Height = 50;
rectangle.Width = 200;
VisualBrush visualBrush = new VisualBrush();
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = Orientation.Horizontal;
Ellipse ellipse = new Ellipse();
ellipse.Height = 10;
ellipse.Width = 10;
ellipse.Fill = new SolidColorBrush(Colors.Blue);
stackPanel.Children.Add(ellipse);
TextBlock textBlock = new TextBlock();
textBlock.Text = "VisualBrush";
stackPanel.Children.Add(textBlock);
Button button = new Button();
button.Content = "按钮";
stackPanel.Children.Add(button);
stackPanel.Background = new SolidColorBrush(Colors.White);
visualBrush.Visual = stackPanel;
rectangle.Fill = visualBrush;

  以上是ImageBrush、DrawingBrush以及VisualBrush三种画刷的示例用法,在实际的应用中,当然不止这么简单的用法,因此这里只算是一个简单的总结,如有错误,欢迎留言指正。

你可能感兴趣的:(WPF学习)