dir.by  
  Поиск  
Компьютер, программы
WPF. Windows Presentation Foundation (standalone .exe file)
 Пример "Рисуем картинку с движением на Canvas" C# WPF 
посмотрели 11757 раз
обновлено: 23 June 2024
Скачать: WpfApp1_imageMove.zip ...
размер: 10 kb

Шаг 1. Создаем новый проект
Шаг 2. Добавим картинку в проект и помечаем как Resource
Сохраните эту картинку к себе на компьютер
Скачать ...
Выбираем картинку с вашего компьютера
Шаг 3. Напишем код
В файле MainWindow.xaml.cs
Сделал свой класс MyCanvas от Canvas
  C#  
public class MyCanvas : Canvas
{
     protected BitmapImage _imageFile1;

     ...

     public void LoadFromResource()
     {
          // load file from resource
          string pathImage = "pack://application:,,,/WpfApp1;component/tree.jpg";
          _imageFile1 = new BitmapImage(new Uri(pathImage, UriKind.Absolute));

          ...
     }

     ...

}


Указываю путь к картинке из Resource
string pathImage = "pack://application:,,,/WpfApp1;component/tree.jpg";


На заметку!
Путь к картинке из Resource это URI в таком общем виде:
pack://application:,,,/[название библиотеки];component/[путь к картинке]
 
При запуске приложения создается MyCanvas и добавляется на главное окно
  C#  
     // MainWindow
public partial class MainWindow : Window
{
     protected MyCanvas _myCanvas;

     ...

     public MainWindow()
     {
          InitializeComponent();

          ...

          // add Canvas
          _myCanvas = new MyCanvas();
          AddChild(_myCanvas);


          ...
     }
}
 
Посмотрим весь код:
  C#     Файл MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WpfApp1
{
     public class MyCanvas : Canvas
     {
          protected BitmapImage _imageFile1;
          protected Point _imagePos1;
          protected Size _imageSize1;
          protected int _imageGoXStep1;

          public void LoadFromResource()
          {
               // load file
               string pathImage = "pack://application:,,,/WpfApp1;component/tree.jpg";
               _imageFile1 = new BitmapImage(new Uri(pathImage, UriKind.Absolute));
               _imagePos1 = new Point(10, 15);
               _imageSize1 = new Size(50, 50);
               _imageGoXStep1 = 1;
          }

          protected override void OnRender(DrawingContext drawingContext)
          {
               drawingContext.DrawImage(_imageFile1, new System.Windows.Rect(_imagePos1, _imageSize1));
          }

          public void MoveObjects()
          {
               _imagePos1.X += _imageGoXStep1;
          }

          public void ReDraw()
          {
               // InvalidateVisual() says Canvas to call OnRender
               InvalidateVisual();
          }
     }

     // MainWindow
     public partial class MainWindow : Window
     {
          protected MyCanvas _myCanvas;
          protected System.Windows.Threading.DispatcherTimer myTimer;
          protected int TimeStepInMilliseconds = 100; // 1/10 second

          public MainWindow()
          {
               InitializeComponent();

               // remove child elements
               Content = null;

               // add Canvas
               _myCanvas = new MyCanvas();
               AddChild(_myCanvas);

               // load image
               _myCanvas.LoadFromResource();

               // timer
               myTimer = new System.Windows.Threading.DispatcherTimer();
               myTimer.Tick += new EventHandler(OnMyTimerTick);
               myTimer.Interval = new TimeSpan(0, 0, 0, 0, TimeStepInMilliseconds); // in milli second
               myTimer.Start();
          }

          private void OnMyTimerTick(object sender, EventArgs e)
          {
               _myCanvas.ReDraw();
               _myCanvas.MoveObjects();
          }
     }
}
 
← Previous topic
Example "Create a Canvas and draw a picture" C# WPF
 
Next topic →
Example "Drawing a picture with motion and sprite animation on Canvas" C# WPF
 
Your feedback ... 5 Comments
guest
7 April 2022 4:46
А как обрезать картинку из нескольких картинок? Как в гифке имеем 5 картинок.
Только нужно обрезать каждую часть и вывести на экран в отдельные image.
guest (7 April 2022 4:51) Чуть подкорректирую вопрос.
Есть картинка, в ней 5 иконок.
Эти 5 иконок нужно разместить на разные image1,image2...image5.
Как это можно реализовать? Гуглю уже сутки, ничего найти не могу.
Через <Image.Clip> не выходит сделать. Ибо там вначале картинка загружается, а потом уже редактируется, идей вообще не осталось :(
answer
admin (7 April 2022 9:24) Есть картинка, в ней 5 иконок.
Вопрос: картинка это файл с каким расширением jpg? ico? png?
answer
guest (7 April 2022 10:57) png, но разве есть разница? answer
admin (7 April 2022 11:13) Мне нужно по работе делать свою задачу поэтому в кратце буду писать как я бы делал. А потом подробнее.

Предлагаю вот такой алгоритм в кратце:

1) Загрузить исходную png картинку в System.Drawing.Image imageSource

2) Кусочки
      a) Вырезаем 1-ый кусок картинки из imageSource т.е. создаем BitmapImage bmpImage1
      b) Вырезаем 2-ой кусок картинки из imageSource т.е. создаем BitmapImage bmpImage2
      c) Вырезаем 3-ий кусок картинки из imageSource т.е. создаем BitmapImage bmpImage3
      d) Вырезаем 4-ый кусок картинки из imageSource т.е. создаем BitmapImage bmpImage4
      e) Вырезаем 5-ый кусок картинки из imageSource т.е. создаем BitmapImage bmpImage5
      
3) Создаем
      a) System.Drawing.Image image1 используя bmpImage1
      b) System.Drawing.Image image2 используя bmpImage2
      c) System.Drawing.Image image3 используя bmpImage3
      d) System.Drawing.Image image4 используя bmpImage4
      e) System.Drawing.Image image5 используя bmpImage5

Если есть вопросы в реализации какй-то части пиши
answer
guest (7 April 2022 11:34) Я разобрался +- как это сделать, но встала другая проблема.
Мне нужно изменить у 3 image картинки на другие, при клике, пытался передать через Binding, но тупо не понимаю как правильно забиндить image и как правильно к нему в коде обратиться.
Ибо Binding имя он не видит, на x:Name(class1) он тоже не отвечает.
Писал так: class1.ViewBox = (0,0,10,10); но тут ошибка.
Вообще не понимаю как программно можно viewbox поменять
answer
admin (7 April 2022 11:46) Чтобы сделать BindImage нужно в cs файле создать переменную вот так:
public ImageSource myImg { get; set; }

еще добавить в код DataContext:
this.DataContext = this;

А в xml файле указать Image вот так:
<Image Source="{Binding myImg}"/>

Использовать x:Name не очень хороший стиль, лучше использовать Binding

Ниже пример Binding изображения на xaml Image:
answer
admin
7 April 2022 12:02
admin
7 April 2022 12:04
admin
7 April 2022 12:09
По поводу ViewBox его можно добавить в этот пример и програмно пробовать поменять но это если надо....
guest (7 April 2022 21:44) Я именно с ViewBox разобраться не могу, вообще не получается изменить координаты из кода answer
guest (7 April 2022 22:28) Всё, разобрался как добавить, спасибо за помощь! answer
guest (7 April 2022 22:35) Хотя мб не совсем правильно сделал, все же посмотрел бы на ваш код answer
guest (7 April 2022 22:43) Когда привязываю 2 значения, они заменяют друг друга и вместе на ставятся на одну картинку, пытаюсь заменить ViewBox и Content answer
admin (8 April 2022 0:57) Фильм смотрел. Попробую добавить Binding Viewbox с Content: answer
admin (8 April 2022 1:06) answer
admin (8 April 2022 1:08) answer
admin (8 April 2022 1:12) Надеюсь написал то что нужно было answer
admin
8 April 2022 1:42
Binding Viewbox с Content и X,Y:
guest (8 April 2022 8:48) понял, спасибо) answer
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
WPF Simple New Application
Creating a New WPF Application | C#
WPF layout
Making a layout with DockPanel and StackPanel in WPF
Events
Example "Get the mouse coordinates when you left-click on TextBlock"| Screen Coordinates and Relative Coordinates | C# WPF application
Example "Get the mouse coordinates when you click the left mouse button on Button"| Screen Coordinates and Relative Coordinates | C# WPF application
Example "Get the mouse coordinates when you left-click on Grid and draw a line"| C# WPF application
Example "When you double-click on Grid, we show the message"| C# WPF application
WPF elements
Label
Example "Setting the text in Label" via c# code | WPF application
FontAwesome icons
Example "I show icons, for the icon I connect the fontawesome5" library | C# WPF application
Example "I make animations for icons, library fontawesome5" | C# WPF application
 <BR>
TextBlock
Example "Set the text in the TextBlock using Binding". Let"s also add double Bindning using INotifyPropertyChanged | C# WPF application
Example "Several TextBlocks (showing the texts) and making the element where mouse (mouse over)" | C# WPF application
Example "Get the mouse coordinates when you left-click on TextBlock"| Screen Coordinates and Relative Coordinates | C# WPF application
Button
Example "Get the mouse coordinates when you click the left mouse button on Button"| Screen Coordinates and Relative Coordinates | C# WPF application
TextBox
Example "Installing and getting text in a TextBox using Binding" | C# WPF application
Example "Set text in TextBox" via c# code | WPF application
 <BR>
TextBox with Place Holder
Example "Showing the Place Holder in TextBox" | WPF application
Example "Showing a Place Holder with an icon in TextBox", for the icon I include the fontawesome5 library | WPF application
 <BR>
TextBox with text validation
Example "Set the text in the TextBox using Binding and do validation (if the text is not correct)" | C# WPF application
 <BR>
ComboBox
Example "In ComboBox, we do text editing. Getting the text using Binding" | C# WPF application
 <BR>
ItemsControl
Example "ItemsControl, button and click handler" | WPF application
Grid
What is Grid in WPF
How to Add RowDefinition, ColumnDefinition to a Grid (with the mouse in the XAML design editor) | C# WPF application
Adding vertical scrolling | WPF application
DataGrid
Example "DataGrid doing bind data", button and click handler in DataGrid, text alignment in DataGrid, scrolling | WPF application
How do I scroll for DataGrid? | C# WPF application
Scrolling for DataGrid (so that scrolling works when we spin the mouse wheel and the mouse is outside the scroll bar) | C# WPF application
How do I color row when I click on row (change background for selected row) in DataGrid? | C# WPF application
How do I highlight a row DataGrid (make background) ? | C# WPF application
Example "DataGrid: sorting the column according to our own algorithm (Custom Sort)" | WPF application
DataGrid inside DataGrid
Example of an employee portfolio with task descriptions: "DataGrid inside DataGrid using RowDetailsTemplate" | WPF application
 <BR>
ListView
Example "In the ListView, expand the column when adding data (auto column width)" | WPF application
Example "In the ListView, we use ItemTemplate DataTemplate" | WPF application
 <BR>
ScrollViewer
Adding vertical scrolling | WPF application
How do I scroll for DataGrid? | C# WPF application
Scrolling for DataGrid (so that scrolling works when we spin the mouse wheel and the mouse is outside the scroll bar) | C# WPF application
Example "Do ScrollBar less(more) in ScrollViewer" | C# WPF application
Resource file
Add an image (jpg, bmp, png) to the project and mark it as Resource | C# WPF application
Image
In the Image element, show the image (jpg, bmp, png) from Resource | C# WPF application
Select the image (jpg, bmp, png) from the computer and show it in the Image element. Saving the image to the database | C# WPF application
Example "In the Image element, make a Binding for Source" | C# WPF application
Example "Convert the base64 text to a Bitmap image and show it in the Image element" | C# WPF application
Example "Open an SVG file and show the image in the Image element" | C# WPF application
 <BR>
Canvas
Example "Create a Canvas and draw a picture" C# WPF
Example "Drawing a picture with movement on Canvas" C# WPF
Example "Drawing a picture with motion and sprite animation on Canvas" C# WPF
 <BR>
Line
How to Draw a Line | C# WPF application
Example "Create and draw a line by left-clicking on Grid"| Grid Line | C# WPF application
Convert the image to XAML Path Geometry
Convert SVG to XAML (using Adobe Illustrator), populate the Path Data Geometry, show the lines on the screen | C# WPF application
Convert SVG to XAML (using Dias SVG to UWP XAML Converter), populate the Path Data Geometry, show the lines on the screen | C# WPF application
How to Convert PNG to SVG to XAML | C# WPF application
Converter SVG to XAML | WPF C#
How to Convert XAML to SVG | C# WPF application
ViewBox
Example "ViewBox Binding for Left, Top, Width, Height, ContetnPresenter binding" | C# WPF application
Width by percentage
Divide the screen vertically (by width) into 2 equal parts of the screen (width1 = 50%, width2 = 50%), use Grid | C# WPF application
Split the screen vertically (by width) into 2 parts (width1 = 70%, width2 = 30%), using Grid | C# WPF application
Example "Set the width of the element as a percentage of the width of the parent element" (width in percentage), write your IValueConverter | C# WPF application
Database (Entity Framework)
Entity Framework in a WPF application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
Creating Your WPF Elements
Example "Create your own WPF element using Style and a new xaml file. The new element is: at the top Title, at the bottom the text in the frame. Using Binding | C# WPF application
Example "Create your new WPF element with your own properties in the new cs and xaml files. In WPF, a new element: Title at the top, text at the bottom, and in the box | C# WPF application
WPF application with Prism library (MVVM design pattern)
Create a new WPF application with Prism Unity (splitting the project into Services, Views, ViewModels folders). MVVM (Model-View-ViewModel) Patern | C#
WPF application with Prism Unity. In the Tab app and splitting into separate xamls using Region.
WPF application with Locator (MVVM design pattern)
Creating a new WPF application with Locator (dividing the project into Views, ViewModels folders)
How do I add Dependency Injection, boot from appsettings.json in a new WPF application?
Automated Tests
Writing an automated test for a WPF C# application (using Nuget.Appium and the AutomationProperties.AutomationId property)
Interview Questions
What is the difference between static resource and dynamic resource? | WPF C#
Additional topics, questions
Open the properties window for a graphic element in WPF application C#
Errors
Error "To run this application, you must install .NET. Would you like to download it now?" | I run WPF the application on C#
Books
WPF Study Books

  Ваши вопросы присылайте по почте: info@dir.by