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

在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. 在 go/golang语言中使用 google Protocol Buffer

    怎么在go语言中实用google protocol Buffer呢? 现在的潮流趋势就是一键搞定,跟ubuntu安装软件一样 go get code.google.com/p/goprotobuf/{ ...

  2. [google面试CTCI] 2-0.链表的创建

    创建链表.往链表中插入数据.删除数据等操作,以单链表为例. 1.使用C语言创建一个链表: typedef struct nd{ int data; struct nd* next; } node; / ...

  3. AJAX异步提交,浏览器总跳出下载界面

    问题: 我在写一个网页的“用户登录”部分时,要将用户名和密码传到后端验证,想在前端用了AJAX异步提交功能,将 用户名密码传到后端,然后后端返回验证结果.但AJAX写好后每次刷新网页都会跳出下载窗口, ...

  4. C语言的一些常见细节

    C语言的一些常见细节 对于C语言,不同的编译器采用了不同的实现,并且在不同平台上表现也不同.脱离具体环境探讨C的细节行为是没有意义的,以下是我所使用的环境,大部分内容都经过测试,且所有测试结果基于这个 ...

  5. 系统架构、网络通信、IM、视频会议技术

    专注于系统架构.网络通信.IM.视频会议技术. 主要作品: ESFramework 强悍的通信框架.P2P框架.群集平台. OMCS 简单易用的 网络语音视频 框架. MFile 语音视频录制组件. ...

  6. 核心C#

    核心C# 内容提要: 声明变量:变量的初始化和作用域:C#的预定义数据类型:在C#程序中使用条件语句.循环和跳转语句指定执行流:枚举:名称空间: Main()方法:基本命令行C#编译器选项:使用Sys ...

  7. 利用pdf2swf将PDF转换成SWF

    将PDF转换成SWF可以使用SWFTools工具中的pdf2swf(http://www.swftools.org/),CSDN快速免积分下载地址http://download.csdn.net/de ...

  8. JS的基本概念

    JS的基本概念 任何语言的核心都必然会描述这门语言最基本的工作原理.而描述的内容通常都要涉及这门语言的语法,操作符,数据类型,内置功能等用于构建复杂解决方案的概念.Ecma-262通过叫做EcmaSc ...

  9. win8商店应用验证,二进制文件是在调试模式下生成的解决方案。

    程序是在release模式下生成的,并且arm和x64通过了验证,但是x86就出现了这个奇葩问题. 搞了半天发现是要把“优化代码”的选项勾上.

  10. ORM查询语言OQL

    ORM查询语言(OQL)简介--高级篇(续):庐山真貌 相关文章内容索引: ORM查询语言(OQL)简介--概念篇 ORM查询语言(OQL)简介--实例篇 ORM查询语言(OQL)简介--高级篇:脱胎 ...