先说结论:实现了在自定义大小的窗口中,加载图片,并在图片上绘制一个矩形框;且在窗口大小改变的情况,保持绘制的矩形框与图片的先对位置不变。

在WinForm中,我们可以很方便地绘制自己需要的内容,在WPF中似乎被限制了,不能够很方便的使用;然后需求有总是奇葩的,所以在这里简单地总结一下。

在WinForm中,如果需要自己绘制,就需要拿到Graphics对象;同样的,我们就希望在WPF也得到一个其同样作用的对象,这个对象就是DrawingContext类的实例对象。

具体来说,就是要重载 UIElement 类的 OnRender 方法。

 public class YourControl : UIElement
{
/// <summary>
/// 重写绘制
/// </summary>
protected override void OnRender(DrawingContext drawingContext)
{
// your logic here
}
}

Talk is cheap, here is the code. 下面的代码完整的组织后,编译可运行,已经调试通了;希望对看到的同学有帮助,有问题,我们也可以探讨。

  • 项目的组织方式;

  • DrawableGrid.cs
 using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging; namespace draw
{
/// <summary>
/// 基本思想
/// 1 在绘制结束时,计算相对于图片真实大小的情况下,绘制的矩形框的大小,及相对于图片的偏移
/// 2 每次刷新绘制前,计算当前窗口大小,及应该绘制的图片的大小,及其偏移
/// 3 每次刷新绘制前,计算绘制的矩形框,相对于当前图片的偏移
/// 其中,
/// 框的偏移及大小,每次使用针对原始图片的数据,作为基础来计算比例,就能够保证即使窗体缩小到0,依旧可以恢复
/// </summary>
public class DrawableGrid : Control
{
#region vars private Point mousedown;
private Point mouseup;
private bool mouseBtnDown = false;
private bool bSelectionDraw = false; private SolidColorBrush mBrush = Brushes.LightBlue;
private Pen mPen = new Pen(Brushes.Red, );
private BitmapImage Img = null; private Grid drawgrid; private Rect curPicRect;
private Rect curSelectRect; private Rect realSelectRect;
private Rect realPicRect; #endregion #region ctors static DrawableGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DrawableGrid), new FrameworkPropertyMetadata(typeof(DrawableGrid)));
} #endregion #region overrides /// <summary>
/// 重写绘制
/// </summary>
protected override void OnRender(DrawingContext drawingContext)
{
if (Img == null)
return; curPicRect = CalcRect(Img.Height, Img.Width, this.ActualHeight, this.ActualWidth);
curSelectRect = CalcResizeRect(curPicRect.X, curPicRect.Y, realSelectRect.X, realSelectRect.Y, realSelectRect.Height, realSelectRect.Width, curPicRect.Height / realPicRect.Height); drawingContext.DrawImage(Img, curPicRect); if (mouseBtnDown)
{
int xmin = (int)Math.Min(mousedown.X, mouseup.X);
int xmax = (int)Math.Max(mousedown.X, mouseup.X);
int ymin = (int)Math.Min(mousedown.Y, mouseup.Y);
int ymax = (int)Math.Max(mousedown.Y, mouseup.Y);
var r = new Rect(xmin, ymin, xmax - xmin, ymax - ymin);
drawingContext.DrawRectangle(mBrush, mPen, r);
} if (bSelectionDraw)
{
drawingContext.DrawRectangle(mBrush, mPen, curSelectRect);
} base.OnRender(drawingContext);
} public override void OnApplyTemplate()
{
drawgrid = GetTemplateChild("drawgrid") as Grid;
if (drawgrid != null)
{
drawgrid.MouseDown += drawgrid_MouseDown;
drawgrid.MouseMove += drawgrid_MouseMove;
drawgrid.MouseUp += drawgrid_MouseUp;
} string picaddr = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "pic", "2.jpg");
Img = new BitmapImage(new Uri(picaddr));
realPicRect = new Rect(, , Img.Width, Img.Height);
} #endregion #region methods /// <summary>
/// 计算图片大小相对于当前的控件大小,应该如何展示
/// </summary>
/// <param name="imgHeight">图片高</param>
/// <param name="imgWidth">图片宽</param>
/// <param name="gridHeight">容器高</param>
/// <param name="gridWidth">容器宽</param>
/// <returns>当前实际应该绘制图片的矩形大小及相对于容器的偏移</returns>
private Rect CalcRect(double imgHeight, double imgWidth, double gridHeight, double gridWidth)
{
Rect rect;
double imgRatio = imgHeight / imgWidth;
double gridRatio = gridHeight / gridWidth; if (imgRatio >= gridRatio)
{
double hi = gridHeight;
double wi = gridHeight / imgRatio; double left = (gridWidth - wi) / ;
double top = ; rect = new Rect(left, top, wi, hi);
}
else
{
double wi = gridWidth;
double hi = gridWidth * imgRatio; double left = ;
double top = (gridHeight - hi) / ; rect = new Rect(left, top, wi, hi);
} return rect;
} /// <summary>
/// 在图片上绘制的框相对于图片的位置
/// </summary>
private Rect CalcResizeRect(double curx, double cury, double lastx, double lasty, double lastheight, double lastwidth, double ratio)
{
double x = curx + lastx * ratio;
double y = cury + lasty * ratio;
double wid = lastwidth * ratio;
double hei = lastheight * ratio;
return new Rect(x, y, wid, hei);
} #endregion #region events private void drawgrid_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed && e.RightButton == MouseButtonState.Released)
{
bSelectionDraw = false;
mouseBtnDown = true;
mousedown = e.GetPosition(drawgrid);
}
} private void drawgrid_MouseMove(object sender, MouseEventArgs e)
{
if (mouseBtnDown)
{
mouseup = e.GetPosition(drawgrid);
this.InvalidateVisual();
}
} private void drawgrid_MouseUp(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Released && e.RightButton == MouseButtonState.Released)
{
bSelectionDraw = true;
mouseBtnDown = false;
mouseup = e.GetPosition(drawgrid); int xmin = (int)Math.Min(mousedown.X, mouseup.X);
int xmax = (int)Math.Max(mousedown.X, mouseup.X);
int ymin = (int)Math.Min(mousedown.Y, mouseup.Y);
int ymax = (int)Math.Max(mousedown.Y, mouseup.Y); var relativeRect = new Rect(xmin, ymin, xmax - xmin, ymax - ymin);
var fullSizeImgRect = CalcRect(Img.Height, Img.Width, Img.Height, Img.Width);
double tempration = fullSizeImgRect.Height / curPicRect.Height;
realSelectRect = CalcResizeRect(fullSizeImgRect.X, fullSizeImgRect.Y, relativeRect.X - curPicRect.X, relativeRect.Y - curPicRect.Y, relativeRect.Height, relativeRect.Width, tempration);
}
} #endregion
}
}
  • DrawableGrid.xaml
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:draw"> <Style TargetType="{x:Type local:DrawableGrid}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DrawableGrid}">
<Grid x:Name="drawgrid" Background="Transparent" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
  • Generic.xaml
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="draw;component/DrawableGrid/DrawableGrid.xaml" />
</ResourceDictionary.MergedDictionaries> </ResourceDictionary>
  • MainWindow.xaml
 <Window x:Class="draw.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:draw"
Title="MainWindow" Height="" Width="">
<local:DrawableGrid />
</Window>
  • MainWindow.xaml.cs
 using System.Windows;

 namespace draw
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}

WPF中自定义绘制内容的更多相关文章

  1. 在WPF中自定义你的绘制(五)

    原文:在WPF中自定义你的绘制(五) 在WPF中自定义你的绘制(五)                                                                   ...

  2. 在WPF中自定义你的绘制(三)

    原文:在WPF中自定义你的绘制(三) 在WPF中自定义你的绘制(三)                                                                  ...

  3. 在WPF中自定义你的绘制(四)

    原文:在WPF中自定义你的绘制(四)                                   在WPF中自定义你的绘制(四)                                 ...

  4. 在WPF中自定义你的绘制(一)

    原文:在WPF中自定义你的绘制(一)   在WPF中自定义你的绘制(一)                                                                 ...

  5. 在WPF中自定义你的绘制(二)

    原文:在WPF中自定义你的绘制(二)   在WPF中自定义你的绘制(二)                                                                 ...

  6. 在VS2005中设置WPF中自定义按钮的事件

    原文:在VS2005中设置WPF中自定义按钮的事件 上篇讲了如何在Blend中绘制圆角矩形(http://blog.csdn.net/johnsuna/archive/2007/08/13/17407 ...

  7. WPF中自定义的DataTemplate中的控件,在Window_Loaded事件中加载机制初探

    原文:WPF中自定义的DataTemplate中的控件,在Window_Loaded事件中加载机制初探         最近因为项目需要,开始学习如何使用WPF开发桌面程序.使用WPF一段时间之后,感 ...

  8. 示例:WPF中自定义MessageService应用DialogHost、Snackbar、NotifyIcon显示各种场景提示消息

    原文:示例:WPF中自定义MessageService应用DialogHost.Snackbar.NotifyIcon显示各种场景提示消息 一.目的:不同交互场景需要提示不同的消息,不同的消息需要用不 ...

  9. 示例:WPF中自定义StoryBoarService在代码中封装StoryBoard、Animation用于简化动画编写

    原文:示例:WPF中自定义StoryBoarService在代码中封装StoryBoard.Animation用于简化动画编写 一.目的:通过对StoryBoard和Animation的封装来简化动画 ...

随机推荐

  1. Js 数组(一):基础应用

    (一) Js 数据类型 分为基本数据类型以及引用类型 基本数据类型有 null,undefined,Boolen,Number,String,还有一种复杂数据类型 Object. var var1 = ...

  2. 实现$.fn.extend 和$.extend函数

    Jquery揭秘系列:实现$.fn.extend 和$.extend函数   前面我们扩展了bind方法和ready函数,这次我要讲一下$.fn.extend 和$.extend函数. 其他的不多说, ...

  3. probuf了解

    人们一直在强调,同 XML 相比, Protobuf 的主要优点在于性能高.它以高效的二进制方式存储,比 XML 小 3 到 10 倍,快 20 到 100 倍. 对于这些 “小 3 到 10 倍”, ...

  4. DOM处理

    DOM处理 这几天整理了一下思路,本来觉得DOM部分会有很多东西,但是忽然发现频繁使用的其实并不太多 class class处理部分主要有四个 hasClass:检查元素是否包含某个class add ...

  5. 调WScript.Shell时报错:Automation 服务器不能创建对象

    我们经常需要通过生成ActiveXObject("WScript.Shell");来调某一exe文件, 如 //设置网页打印的页眉页脚为空 var HKEY_Root,HKEY_P ...

  6. 绘制基本图形和线型(StrokeStyle)的设置详解

    绘制基本图形和线型(StrokeStyle)的设置详解 目前,在博客园上,相对写得比较好的两个关于Direct2D的教程系列,分别是万一的Direct2D系列和zdd的Direct2D系列.有兴趣的网 ...

  7. OpenCV 4 Python高级配置—安装setuptools,matplotlib,six,dateutil,pyparsing 完整过程

    Matplotib 是python 的一个绘图库,里头有各种各样的绘图方法,可以用Matplotib 显示图像,放大图像,保存图像等等,对于OpenCV处理图像具有非常大的帮助.但是,安装Matplo ...

  8. [修]python普通继承方式和super继承方式

    [转]python普通继承方式和super继承方式 原文出自:http://www.360doc.com/content/13/0306/15/9934052_269664772.shtml 原文的错 ...

  9. Objective-C之run loop详解

    Objective-C之run loop详解 做了一年多的IOS开发,对IOS和Objective-C深层次的了解还十分有限,大多还停留在会用API的级别,这是件挺可悲的事情.想学好一门语言还是需要深 ...

  10. lll

    //// whywhy unsigned int T = 1; ~T = 4294967294; T = 2;~T= 4294967293 ;T = 0;~T=4294967295; int T = ...