C# 实现的图片盖章功能,支持拖拽、旋转、放缩、保存

实现图片盖章功能,在图片上点击,增加“图章”小图片,可以拖拽“图章”到任意位置,也可以点击图章右下角园框,令图片跟着鼠标旋转和放缩。

操作方法:1.点击增加“图章”2.选中移动图标3.点中右下角放缩旋转图章。

效果图:






实现代码如下:

1.  窗口Xaml代码


代码如下:

<Window x:Class="Lenovo.YogaPaster.ImageEditWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ImageEditWindow" Height="300" Width="300">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="20*"/>
      <RowDefinition  Height="*"/>
    </Grid.RowDefinitions>
    <Canvas x:Name="canvas"
      Background="Yellow" />
    <Button Content="保存成图片" Click="Button_Click_1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  </Grid>
</Window>

2.  窗口后台代码:


代码如下:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Lenovo.YP.Utils;
using Microsoft.Win32;
using Point = System.Windows.Point;

namespace Lenovo.YogaPaster
{
  /// <summary>
  /// ImageEditWindow.xaml 的交互逻辑
  /// </summary>
  public partial class ImageEditWindow : Window
  {
    public ImageEditWindow()
    {
      InitializeComponent();
      this.Loaded += (sender, e) =>
      {
        canvas.MouseLeftButtonDown += canvas_MouseLeftButtonDown;
      };
    }
    private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      PhotoEditHelper.CommomMaxZIndex++;
      var image = new MoveImage { ContainerCanvas = canvas };
      Point point = e.GetPosition(canvas);
      image.CreateImage(point);
    }
    /// <summary>
    /// 保存方法
    /// </summary>
    public void SavePicture()
    {
      //TODO: openFile对话框
      SaveFileDialog saveFileDialog = new SaveFileDialog();
      saveFileDialog.FileName = "图片"; // Default file name
      saveFileDialog.DefaultExt = ".bmp"; // Default file extension
      saveFileDialog.Filter = "图片文件 (.bmp)|*.bmp"; // Filter files by extension

// Show save file dialog box
      Nullable<bool> result = saveFileDialog.ShowDialog();

// Process save file dialog box results
      if (result == true)
      {
        // Save document
        string filename = saveFileDialog.FileName;
        if (File.Exists(filename))
        {
          File.Delete(filename);
        }
        BitmapSource bitmapSource = PictureMergeHelper.CreateNotRanderElementScreenshot(canvas, 1800, 1080);
        BitmapEncoder bitmapEncoder = new BmpBitmapEncoder();
        bitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapSource));
        FileStream fileStream = new FileStream(filename, FileMode.Create);
        bitmapEncoder.Save(fileStream);
        fileStream.Dispose();
      }
    }

private void Button_Click_1(object sender, RoutedEventArgs e)
    {
      SavePicture();
    }
  }
}

3. MoveImage 类文件如下:


代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Lenovo.YP.Utils
{
  /// <summary>
  /// 添加一个image控件,并实现拖动效果
  /// </summary>
  public class MoveImage
  {
    #region 字段
    private int m_ZIndex;
    /// <summary>
    /// 当前图章的位置
    /// </summary>
    ///
    /// <summary>
    /// 旋转图标的起始位置
    /// </summary>
    private Point m_ImageRoundStartOffset;
    /// <summary>
    /// 旋转图标的当前位置
    /// </summary>
    private Point m_ImageRoundOffset;
    /// <summary>
    /// 标识图章是否被拖拽
    /// </summary>
    private bool m_IsDragging;
    /// <summary>
    /// 标识旋转图标是否被是否被拖拽
    /// </summary>
    private bool m_IsimageRoundDragging;
    /// <summary>
    /// 图章的父容器
    /// </summary>
    public Canvas ContainerCanvas { get; set; }
    /// <summary>
    /// 图章图片
    /// </summary>
    private Image m_FlogImage;
    /// <summary>
    /// 旋转按钮图片
    /// </summary>
    private Image m_RotateImage;
    /// <summary>
    /// 图章和旋转图片的容器
    /// </summary>
    private Grid m_MoveImageGrid;
    /// <summary>
    /// 选转
    /// </summary>
    private RotateTransform m_ImageRotate;
    /// <summary>
    /// 缩放
    /// </summary>
    private ScaleTransform m_ImageScale;
    /// <summary>
    /// 上次位置
    /// </summary>
    private Point m_OldPos;
    #endregion

public MoveImage()
    { }
    /// <summary>
    /// 创建一个图标
    /// </summary>
    /// <param name="position">图标的位置</param>
    public void CreateImage(Point position)
    {
      #region 设置布局
      m_FlogImage = new Image
      {
        //Width = 100,
        //Height = 100,
        Source = new BitmapImage(new Uri("/Images/shuzi.jpg", UriKind.RelativeOrAbsolute))
      };
      m_RotateImage = new Image
      {
        Width = 20,
        Height = 20,
        Source = new BitmapImage(new Uri("/Images/round.jpg", UriKind.RelativeOrAbsolute))
      };
      m_RotateImage.HorizontalAlignment = HorizontalAlignment.Right;
      m_RotateImage.VerticalAlignment = VerticalAlignment.Bottom;
      m_RotateImage.Visibility = Visibility.Hidden;
      m_MoveImageGrid = new Grid();
      m_MoveImageGrid.Width = 110;
      m_MoveImageGrid.Height = 110;
      m_MoveImageGrid.Children.Add(m_FlogImage);
      m_MoveImageGrid.Children.Add(m_RotateImage);
      m_MoveImageGrid.MouseEnter += RootGridMouseEnter;
      m_MoveImageGrid.MouseLeave += RootGridMouseLeave;
      m_RotateImage.MouseLeftButtonDown += imageRound_MouseLeftButtonDown;
      m_RotateImage.MouseMove += imageRound_MouseMove;
      m_RotateImage.MouseLeftButtonUp += imageRound_MouseLeftButtonUp;
      // Image in den Vordergrund bringen
      Canvas.SetZIndex(m_MoveImageGrid, m_ZIndex++);
      #endregion
      // Event Handler für das Image installieren
      m_MoveImageGrid.MouseLeftButtonDown += RootGridMouseLeftButtonDown;
      m_MoveImageGrid.MouseLeftButtonUp += RootGridMouseLeftButtonUp;
      m_MoveImageGrid.MouseMove += RootGridMouseMove;
      // Image leicht transparent machen
      m_MoveImageGrid.Opacity = 0.8;
      m_ImageRotate = new RotateTransform(0, 0, 0);
      m_ImageScale = new ScaleTransform();
      //m_ImageScale.ScaleX = 1;
      //m_ImageScale.ScaleY = 1;
      TransformGroup transformGroup = new TransformGroup();
      transformGroup.Children.Add(m_ImageRotate);
      transformGroup.Children.Add(m_ImageScale);
      m_MoveImageGrid.RenderTransform = transformGroup;
      //m_ImageScale111 = new ScaleTransform();
      //m_ImageScale111.ScaleX = 0.5;
      //m_ImageScale111.ScaleY = 0.5;
      //imageRound.RenderTransform = m_ImageScale111;
      m_MoveImageGrid.RenderTransformOrigin = new Point(0.5, 0.5);
      // Image positionieren
      var pos = position;
      Canvas.SetLeft(m_MoveImageGrid, pos.X - (m_MoveImageGrid.Width / 2));
      Canvas.SetTop(m_MoveImageGrid, pos.Y - (m_MoveImageGrid.Height / 2));
      // Image zum Canvas hinzufügen
      ContainerCanvas.Children.Add(m_MoveImageGrid);
    }

/// <summary>
    /// 控制旋转图标隐藏
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void RootGridMouseLeave(object sender, MouseEventArgs e)
    {
      m_RotateImage.Visibility = Visibility.Hidden;
    }

/// <summary>
    /// 控制选择图标显示
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void RootGridMouseEnter(object sender, MouseEventArgs e)
    {
      m_RotateImage.Visibility = Visibility.Visible;
    }

#region 控制盖章的移动
    private void RootGridMouseMove(object sender, MouseEventArgs e)
    {
      if (m_IsDragging)
      {
        var pos = e.GetPosition(ContainerCanvas);
        Canvas.SetLeft(m_MoveImageGrid, Canvas.GetLeft(m_MoveImageGrid) + pos.X - m_OldPos.X);
        Canvas.SetTop(m_MoveImageGrid, Canvas.GetTop(m_MoveImageGrid) + pos.Y - m_OldPos.Y);
        m_OldPos = pos;
      }
    }

private void RootGridMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
      var grid = sender as Grid;

// Canvas.SetZIndex(image, m_ZIndex++);
      // Bild wieder leicht transparent machen
      grid.Opacity = 0.8;
      grid.ReleaseMouseCapture();
      m_IsDragging = false;
    }

private void RootGridMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {

var grid = sender as Grid;

// auf "nicht"-transparent setzen
      grid.Opacity = 1;

// Position des Pointers relativ zum Bild speichern
      m_OldPos = e.GetPosition(ContainerCanvas);

// isDragging auf true setzen für MouseMove
      m_IsDragging = true;
      // Image in den Vordergrund bringen
      Canvas.SetZIndex(grid, PhotoEditHelper.CommomMaxZIndex++);
      // Den Pointer einfangen. Bei schnellen Bewegungen kann der
      // Pointer aus dem Image bewegt werden. Damit die Pointer-
      // Events weiterhin stattfinden, wird der Pointer eingefangen. 
      grid.CaptureMouse();
      // als behandelt markieren, damit nicht noch der
      // PointerPressed-Event Handler des Canvas aufgerufen wird.
      e.Handled = true;
    }
    #endregion

#region 控制图章的旋转
    private void imageRound_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
      var image = sender as Image;

m_MoveImageGrid.Opacity = 1;
      image.ReleaseMouseCapture();
      m_IsimageRoundDragging = false;
    }

private void imageRound_MouseMove(object sender, MouseEventArgs e)
    {
      if (m_IsimageRoundDragging)
      {
        //鼠标当前点的坐标
        m_ImageRoundOffset = e.GetPosition(ContainerCanvas);
        m_ImageScale.ScaleX =
          m_ImageScale.ScaleY = GetLength(currCenter, m_ImageRoundStartOffset, m_ImageRoundOffset);
        m_ImageRotate.Angle = GetAngle(currCenter, m_ImageRoundStartOffset, m_ImageRoundOffset) - 45;
      }
    }

private Point currCenter;
    private void imageRound_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      var image = sender as Image;
      m_MoveImageGrid.Opacity = 1;

//中心点坐标
      currCenter = new Point(Canvas.GetLeft(m_MoveImageGrid) + m_MoveImageGrid.Width / 2, Canvas.GetTop(m_MoveImageGrid) + m_MoveImageGrid.Height / 2);
      m_ImageRoundStartOffset = new Point(currCenter.X + m_MoveImageGrid.Width / 2, currCenter.Y);
      m_IsimageRoundDragging = true;
      Canvas.SetZIndex(m_MoveImageGrid, PhotoEditHelper.CommomMaxZIndex++);
      image.CaptureMouse();
      e.Handled = true;
    }

/// 根据余弦定理求两个线段夹角
    /// </summary> 
    /// <param name="origin">原点</param> 
    /// <param name="start">start点</param> 
    /// <param name="end">end点</param> 
    /// <returns></returns> 
    private double GetAngle(Point origin, Point start, Point end)
    {
      double cosfi = 0, fi = 0, norm = 0;
      double dsx = start.X - origin.X;
      double dsy = start.Y - origin.Y;
      double dex = end.X - origin.X;
      double dey = end.Y - origin.Y;

cosfi = dsx * dex + dsy * dey;
      norm = (dsx * dsx + dsy * dsy) * (dex * dex + dey * dey);
      if (norm == 0) return 0; // origin和end坐标一样
      cosfi /= Math.Sqrt(norm);

if (cosfi >= 1.0) return 0;
      if (cosfi <= -1.0) return 180;
      fi = Math.Acos(cosfi);

double angle = 180 * fi / Math.PI;

if (dey > 0)
      {
        return angle;
      }
      return -angle;
    }

private double GetLength(Point origin, Point start, Point end)
    {
      double dex = end.X - origin.X;
      double dey = end.Y - origin.Y;
      double dsx = start.X - origin.X;
      double dsy = start.Y - origin.Y;
      double startLength = Math.Sqrt(Math.Pow(dsx, 2) + Math.Pow(dsy, 2));
      double endLength = Math.Sqrt(Math.Pow(dex, 2) + Math.Pow(dey, 2));
      return endLength / startLength;
    }

#endregion
  }

(0)

相关推荐

  • C#利用控件拖拽技术制作拼图游戏

    主要实现的功能: 1.程序附带多张拼图随机拼图. 2.可手动添加拼图. 3.游戏成功判断. 4.30秒超时判断. Puzzle.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms

  • C#组件FormDragger窗体拖拽器详解

    适用:.net2.0+ winform项目 介绍: 类似QQ.迅雷等讲究UI体验的软件,都支持在窗口内多处地方拖动窗口,而不必老实巴交的去顶部标题栏拖,这个组件就是让winform也能这样随性拖拽,随性度或更甚.先看效果: 可拖拽的地方包括不限于: 窗体.Panel.GroupBox.TabControl等容器控件的空白区: 菜单栏.工具栏.状态栏等bar的空白区,以及无效项目: Label.PictureBox.ProgressBar等通常不与鼠标交互的控件: 一切无效控件(Enabled为f

  • C#实现Dev Grid拖拽移动行的方法

    本文实例讲述了C#实现Dev Grid拖拽移动行的方法.分享给大家供大家参考.具体如下: 完整实例代码点击此处本站下载.     拖拽时带行截图效果 实现代码如下: /// <summary> /// 拖拽帮助类 /// </summary> public static class DragHelper { /// <summary> /// BandedGridView 拖拽 /// </summary> /// <param name="

  • C# 实现的图片盖章功能,支持拖拽、旋转、放缩、保存

    实现图片盖章功能,在图片上点击,增加"图章"小图片,可以拖拽"图章"到任意位置,也可以点击图章右下角园框,令图片跟着鼠标旋转和放缩. 操作方法:1.点击增加"图章"2.选中移动图标3.点中右下角放缩旋转图章. 效果图: 实现代码如下: 1.  窗口Xaml代码 复制代码 代码如下: <Window x:Class="Lenovo.YogaPaster.ImageEditWindow"    xmlns="htt

  • jQuery插件实现文件上传功能(支持拖拽)

    先贴上源代码地址,点击获取.然后直接进入主题啦,当然,如果你觉得我有哪里写的不对或者欠妥的地方,欢迎留言指出.在附上一些代码之前,我们还是先来了解下,上传文件的时候需要利用的一些必要的知识. 首先我们要说的就是FileReader对象,这是一个HTML5提出的,专门用来异步的读取用户计算机上文件的对象,这里有详细的介绍.所以如果我们想要使用它,那么首先我们得先创建一个FileReader对象.  var fr = new FileReader() 1.这个对象拥有五个方法: 下面附上一个例子:

  • JS文件/图片从电脑里面拖拽到浏览器上传文件/图片

    1.效果展示 2.html 代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./upload.js"></script> <style> #drop img{width: 100px;he

  • jquery插件jquery.nicescroll实现图片无滚动条左右拖拽的方法

    本文实例讲述了jquery插件jquery.nicescroll实现图片无滚动条左右拖拽的方法.分享给大家供大家参考.具体如下: 这里介绍jQuery图片左右拖拽特效,无滚动条,将多张图片组合在一起形成的效果,插件使用的是jquery.nicescroll.js,拖动过程中不会出现滚动条,这样更美观了一些,若需要此效果,可参见下边框中的代码. 运行效果截图如下: 具体代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitiona

  • UGUI ScrollRect实现带按钮翻页支持拖拽

    本文实例为大家分享了UGUI ScrollRect带按钮翻页支持拖拽的具体代码,供大家参考,具体内容如下 using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections.Generic; using System; /// <summary> /// 略知CSharp /// </summary> p

  • Unity UI实现拖拽旋转

    本文实例为大家分享了Unity UI实现拖拽旋转的具体代码,供大家参考,具体内容如下 跟随鼠标旋转 第一种效果是跟随鼠标旋转,原理是计算下鼠标位置与拖拽物体的相对位移 旋转方向即可 注意转换对应空间坐标 新建脚本mono类继承 IBeginDragHandler, IDragHandler, IEndDragHandler 接口 [SerializeField] private Canvas m_Canvas; private Vector3? CalculateWorldToScreenPos

  • jQuery实现元素拖拽并cookie保存顺序的方法

    本文实例讲述了jQuery实现元素拖拽并cookie保存顺序的方法.分享给大家供大家参考,具体如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"&

  • JS前端canvas交互实现拖拽旋转及缩放示例

    目录 正文 拖拽 旋转 缩放 小结 正文 到目前为止,我们已经能够对物体进行点选和框选的操作了,但是这还不够,因为并没有什么实际性的改变,并且画布看起来也有点呆板,所以这个章节的主要目的就是让画布中的物体活起来,其实就是增加一些常见的交互而已啦,比如拖拽.旋转和缩放.这是这个系列最重要的章节之一,希望能够对你有所帮助. 拖拽 先来说说拖拽平移的实现吧,因为它最为简单

  • Jquery拖拽并简单保存的实现代码

    但是如何保存顺序呢,想到了cookie,但是用如何用cookie保存顺序呢,直接保存html代码下次读取覆盖可以,但是总感觉内容多的话 保存的东西比较多,后用ui插件获取id保存id在读取实现了顺序的保存,废话不多说..直接看代码... 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-tran

  • 基于vue-simplemde实现图片拖拽、粘贴功能

    项目使用的是vue框架,需要一个markdown的编辑框,就在npm上找了一下,发现simplemde挺不错的,由于我比较懒,就顺便在npm又搜了一下,找到了vue-simplemde这个 package ,那就开始使用它吧. 但是这个 vue-simplemde 不支持图片拖拽上传.粘贴上传,也不能说是因为这个 vue-simplemde ,因为 vue-simplemde 只是对 simplemde 的基础上封装成一个Vue插件.所以最后还是由于 simplemde 没有提供相关的功能,但是

随机推荐