如何在WPF中的现有BitmapSource上绘制一条线?

时间:2010-08-16 15:46:39

标签: wpf geometry bitmapsource

我想在WPF应用程序中的现有BitmapSource对象上绘制一条线(或任何几何形状)。最好的方法是什么?

BitmapSource是BitmapSource.Create(...)调用的结果。

由于

  • 罗曼

1 个答案:

答案 0 :(得分:0)

下面的示例将显示从BitmapSource创建的图像,其上面有一条红线。那是你想要实现的目标吗?

XAML:

<Window x:Class="WpfApplication.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid Background="LightBlue">
        <Image Source="{Binding Path=ImageSource}" />
        <Line 
            Stroke="Red" StrokeThickness="10" 
            X1="0" 
            Y1="0" 
            X2="{Binding Path=ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" 
            Y2="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" />
    </Grid>
</Window>

代码背后:

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WpfApplication
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            DataContext = this;
        }

        public BitmapSource ImageSource
        {
            get
            {
                PixelFormat pf = PixelFormats.Bgr32;
                int width = 200;
                int height = 200;
                int rawStride = (width * pf.BitsPerPixel + 7) / 8;
                byte[] rawImage = new byte[rawStride * height];

                Random value = new Random();
                value.NextBytes(rawImage);

                return BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, rawStride);
            }
        }
    }
}