首页 > 其他分享 >WPF canvas Draw line , ellipse and rectangle, save canvas and contents as picture

WPF canvas Draw line , ellipse and rectangle, save canvas and contents as picture

时间:2024-09-26 17:45:01浏览次数:1  
标签:System picture canvas void Draw cvs using new elp

//xaml
<Window x:Class="WpfApp417.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp417"
        mc:Ignorable="d"
        WindowState="Maximized"
        KeyDown="Window_KeyDown"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Set Background" Click="SetBackgroundClick" Width="150" Background="Cyan"/>
            <RadioButton x:Name="drawLinesRadio" IsChecked="True" Content="Draw Lines" GroupName="DrawShapeGroup"/>
            <RadioButton x:Name="drawEllipseRadio" Content="Draw Ellipse" GroupName="DrawShapeGroup"/>
            <RadioButton x:Name="drawRectRadio" Content="Draw Rect" GroupName="DrawShapeGroup"/>
            <Button Content="Save As Picture" Click="SavePicClick" Width="150" Background="Cyan"/>
        </ToolBar>
        <Canvas Grid.Row="1" x:Name="cvs"
                MouseDown="cvs_MouseDown"
                MouseMove="cvs_MouseMove"
                MouseUp="cvs_MouseUp">
            <Canvas.Background>
                <ImageBrush ImageSource="Images/1.jpg"/>
            </Canvas.Background>
            <Canvas.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Save As Picture" 
                              Click="SavePicClick"/>
                </ContextMenu>
            </Canvas.ContextMenu>
        </Canvas>
    </Grid>
</Window>


//xaml.cs

using Microsoft.Win32;
using System;
using System.Collections.Generic;
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.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfApp417
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.S)
            {
                SaveCvsAsPicture();
            }
        }

        private void SaveCvsAsPicture()
        {
            SaveCanvasAndContentAsPicture();
        }


        Point oldPt { get; set; }
        Point newPt { get; set; }

        bool isDrawing = false;
        private void cvs_MouseDown(object sender, MouseButtonEventArgs e)
        {
            oldPt = e.GetPosition(cvs);
        }

        private void cvs_MouseMove(object sender, MouseEventArgs e)
        {
            isDrawing = true;
        }

        private void cvs_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (drawLinesRadio.IsChecked == true)
            {
                DrawLineInCanvas(e);
            }
            else if(drawEllipseRadio.IsChecked==true)
            {
                DrawEllipseInCanvas(e);
            }
            else if(drawRectRadio.IsChecked==true)
            {
                DrawRectangleInCanvas(e);
            }
        }

        private void DrawRectangleInCanvas(MouseButtonEventArgs e)
        {
            Rectangle rect = new Rectangle();
            newPt = e.GetPosition(cvs);
            double rectWidth = newPt.X - oldPt.X;
            double rectHeight=newPt.Y - oldPt.Y;

            rect.Width = Math.Abs(rectWidth);
            rect.Height =Math.Abs(rectHeight);
            rect.Stroke = new SolidColorBrush(Colors.Blue);
            rect.StrokeThickness = 5;
            rect.Fill = new SolidColorBrush(Colors.Red);
            Canvas.SetLeft(rect, e.GetPosition(cvs).X - rectWidth);
            Canvas.SetTop(rect, e.GetPosition(cvs).Y - rectHeight);
            if (!cvs.Children.Contains(rect))
            {
                cvs.Children.Add(rect);
            }
        }

        private void DrawEllipseInCanvas(MouseButtonEventArgs e)
        {
            Ellipse elp = new Ellipse();
            newPt = e.GetPosition(cvs);
            double elpWidth= (newPt.X - oldPt.X)*2;
            double elpHeight=(newPt.Y - oldPt.Y)*2;
            elp.Width =Math.Abs(elpWidth);
            elp.Height =Math.Abs(elpHeight);
            elp.Stroke = new SolidColorBrush(Colors.Blue);
            elp.StrokeThickness = 5;
            elp.Fill = new SolidColorBrush(Colors.Red);
            Canvas.SetLeft(elp, e.GetPosition(cvs).X - elp.Width/2);
            Canvas.SetTop(elp, e.GetPosition(cvs).Y-elp.Height/2);
            if (!cvs.Children.Contains(elp))
            {
                cvs.Children.Add(elp);
            }
        }

        private void DrawLineInCanvas(MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left
                && e.ButtonState == MouseButtonState.Released
                && isDrawing)
            {
                newPt = e.GetPosition(cvs);
                Line ln = new Line();
                ln.X1 = oldPt.X;
                ln.Y1 = oldPt.Y;
                ln.X2 = newPt.X;
                ln.Y2 = newPt.Y;
                ln.Stroke = new SolidColorBrush(Colors.Red);
                ln.StrokeThickness = 5;
                ln.StrokeEndLineCap = PenLineCap.Triangle;
                if (!cvs.Children.Contains(ln))
                {
                    cvs.Children.Add(ln);
                }
                isDrawing = false;
            }
        }

        private void SavePicClick(object sender, RoutedEventArgs e)
        {
            SaveCanvasAndContentAsPicture();           
        }

        private void SaveCanvasAndContentAsPicture()
        {
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)cvs.ActualWidth,
               (int)cvs.ActualHeight, 96d, 96d, PixelFormats.Pbgra32);
            renderTargetBitmap.Render(cvs);

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "JPG Files|*.jpg|PNG Files|*.png|All Files|*.*";
            dialog.FileName = $"Pic{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.jpg";
            if (dialog.ShowDialog() == true)
            {
                using (FileStream fs = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
                    encoder.Save(fs);
                    MessageBox.Show($"Saved in{dialog.FileName}", "Save Succesfully!", MessageBoxButton.OK);
                }
            }
        }

        private void SetBackgroundClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Jpg Files|*.jpg|Png Files|*.png|All Files|*.*";
            if (dialog.ShowDialog() == true)
            {
                if (File.Exists(dialog.FileName))
                {
                    BitmapImage bmp = new BitmapImage();
                    bmp.BeginInit();
                    bmp.UriSource=new Uri(dialog.FileName);
                    bmp.EndInit();
                    bmp.Freeze();
                    ImageBrush imgBrush = new ImageBrush(bmp);
                    cvs.Background = imgBrush;
                }
            }
        }
    }
}

 

Draw line

 

 

Draw Ellipse

 

 

 

Draw rectangles

 

标签:System,picture,canvas,void,Draw,cvs,using,new,elp
From: https://www.cnblogs.com/Fred1987/p/18433967

相关文章

  • WPF InkCanvas selection mode, save all/selected strokes, load strokes file, sav
    //xaml<Windowx:Class="WpfApp416.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......
  • 【Canvas与徽章】金穗蓝盾徽章
    【成图】【代码】<!DOCTYPEhtml><htmllang="utf-8"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><head><title>金穗蓝盾draft1</title><styletype="text/css&qu......
  • 【Canvas与徽章】庆祝建国75周年徽章
    【成图】【代码】<!DOCTYPEhtml><htmllang="utf-8"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><head><title>庆祝建国75周年</title><styletype="text/css"......
  • 手写板 canvas
    <!doctypehtml><html><head><metacharset="utf-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge,chrome=1"><metaname="viewport"content="width=device-width">&......
  • Canvas简历编辑器-Monorepo+Rspack工程实践
    Canvas简历编辑器-Monorepo+Rspack工程实践 Canvas简历编辑器-Monorepo+Rspack工程实践在之前我们围绕Canvas聊了很多代码设计层面的东西,在这里我们聊一下工程实践。在之前的文中我也提到过,因为是本着学习的态度以及对技术的好奇心来做的,所以除了一些工具类的库例如 ArcoDe......
  • WPF Image show picture in high resolution periodically via System.Timers.Timer
    <Windowx:Class="WpfApp411.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • 【Canvas与诗词】铁马冰河入梦来
    【成图】【代码】<!DOCTYPEhtml><htmllang="utf-8"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><head><title>金红圈铁马冰河入梦来</title><styletype="text/css&quo......
  • Drawon——崭露头角的创新办公平台
    Drawon是一款多功能的可视化创作工具,融合了流程图绘制、思维导图、绘画和在线PPT等多种功能,同时也是设计知识的共创、协作与分享平台。基于新一代云操作系统,它支持云同步,方便创建团队空间并统一管理所有设计文件。团队成员能够随时在线查看和编辑文件,实现真正的无缝协作。Draw......
  • 绘制印章的开源工具DrawStampUtils使用
    最近写了一个绘制印章的工具DrawStampUtils,具有比较完整的印章修改效果,定制化度较高,git地址(https://github.com/xxss0903/drawstamputils),也可以在npmjs中搜索DrawStampUtils即可//将要绘制的canvas组件的引用传入,还有就是对应的毫米转像素的大小传入即可conststampCanva......
  • Python可视化过程中.pictures.add这里一直报错,不明原因
    大家好,我是Python进阶者。一、前言前几天在Python白银交流群【沐子山树】问了一个Python可视化的问题,问题如下:importmatplotlib.pyplotasplt#创建一个简单的图表fig,ax=plt.subplots()ax.plot([1,2,3,4])ax.set_ylabel('somenumbers')#保存图表为PNG文件temp......