Рисование в PictureBox
×

Рисование в PictureBox

Для начала добавим в форму pictureBox1 и timer1.

1. Рисуем прямую

В код timer1 добавляем:

private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
                 Graphics ^ g = pictureBox1->CreateGraphics();
                 Pen^ p = gcnew Pen( Color::Blue,2);            //выбираем цвет прямой и её толщину                
                 Point pt1 = Point(100, 20);
                 Point pt2 = Point(100, 100);
                 g->DrawLine(p, pt1, pt2);                      //соединяем точки и получаем прямую
     }

В код MyForm.h добавляем: 

private: System::Void MyForm_Load(System::Object^  sender, System::EventArgs^  e) {
              timer1->Start();
    }

2. Реализуем вращение прямой по правилу

В самом верху, после #pragma once объявим #include "math.h".
А после namespace ... { объявим int i; и double x2, y2; .
  
Теперь в коде timer1 напишем:

         private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
             x2 = 100 + (20 - 100)*cos(-i*3.14 / 100);
             y2 = 100 + (20 - 100)*sin(-i*3.14 / 100);
             Graphics ^ g = pictureBox1->CreateGraphics();
             SolidBrush^ br = gcnew SolidBrush(Color::White);
             g->FillRectangle(br, 0, 0, pictureBox1->Width, pictureBox1->Height); //очистка
             Pen^ p = gcnew Pen( Color::Blue,2);
             Point pt1 = Point(x2, y2);
             Point pt2 = Point(100, 100);
             g->DrawLine(p, pt1, pt2);
             i++;
         }

3. Реализуем перемещение этой прямой

В коде timer1 напишем:

   private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
         x2 = 100 + i;
         Graphics ^ g = pictureBox1->CreateGraphics();
         SolidBrush^ br = gcnew SolidBrush(Color::White);
         g->FillRectangle(br, 0, 0, pictureBox1->Width, pictureBox1->Height); //очистка
         Pen^ p = gcnew Pen( Color::Blue,2);
         Point pt1 = Point(x2, 20);
         Point pt2 = Point(x2, 100);
         g->DrawLine(p, pt1, pt2);
         i++;
       }

4. Рисуем прямоугольник и масштабируем его

В коде timer1 напишем:

private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
     x2 = 1 + i;
     y2 = 2 + i*2;
     Graphics ^ g = pictureBox1->CreateGraphics();
     SolidBrush^ br = gcnew SolidBrush(Color::White);
     g->FillRectangle(br, 0, 0, pictureBox1->Width, pictureBox1->Height); //очистка
     SolidBrush^ br1 = gcnew SolidBrush(Color::CadetBlue);
     g->FillRectangle(br1, 10, 10, x2, y2);                               //прямоугольник
     i++;
           }

5. Рисуем эллипс или окружность и сегмент

В коде timer1 напишем:

private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
     Graphics ^ g = pictureBox1->CreateGraphics();
     SolidBrush^ br = gcnew SolidBrush(Color::Red);
     g->FillEllipse(br, 10, 10, 100, 200);         //эллипс
     g->FillPie(br, 140, 140, 90, 90, 0, 45);      //сегмент        
    }

Особенности рисования.

Из точки, заданной первыми двумя координатами, условно проводится квадрат со сторонами, заданными вторыми
двумя числами. Затем в этот квадрат вписывается эллипс. С сегментом то же самое.
Точка с координатами (0.0) находится в верхнем левом углу. 

Вот небольшая программка, включающая в себя основные элементы рисования.

Для запуска просто вставьте этот код и вместо ДЗ8 напишите название своего проекта!!!

#pragma once

#include "math.h"

namespace ДЗ8 {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;

	/// <summary>
	/// Сводка для Form1
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
		
		int i, x2, y2,y ,yc;
		Graphics ^ g;
		Pen^ p;
		Pen^ p1;
		SolidBrush^br;
		SolidBrush^br1;
		SolidBrush^br2;
		SolidBrush^br3;
		array<Point>^pts;
	public:
		Form1(void)
		{
			InitializeComponent();
			//
			//TODO: добавьте код конструктора
			//
		}

	protected:
		/// <summary>
		/// Освободить все используемые ресурсы.
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}
	private: System::Windows::Forms::PictureBox^  pictureBox1;
	protected:
	private: System::Windows::Forms::Timer^  timer1;
	private: System::ComponentModel::IContainer^  components;

	private:
		/// <summary>
		/// Требуется переменная конструктора.
		/// </summary>


#pragma region Windows Form Designer generated code
		/// <summary>
		/// Обязательный метод для поддержки конструктора - не изменяйте
		/// содержимое данного метода при помощи редактора кода.
		/// </summary>
		void InitializeComponent(void)
		{
			this->components = (gcnew System::ComponentModel::Container());
			this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
			this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
			(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit();
			this->SuspendLayout();
			// 
			// pictureBox1
			// 
			this->pictureBox1->Location = System::Drawing::Point(13, 13);
			this->pictureBox1->Name = L"pictureBox1";
			this->pictureBox1->Size = System::Drawing::Size(641, 411);
			this->pictureBox1->TabIndex = 0;
			this->pictureBox1->TabStop = false;
			this->pictureBox1->Click += gcnew System::EventHandler(this, &Form1::pictureBox1_Click);
			// 
			// timer1
			// 
			this->timer1->Interval = 40;
			this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(666, 436);
			this->Controls->Add(this->pictureBox1);
			this->Name = L"Form1";
			this->Text = L"Form1";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit();
			this->ResumeLayout(false);

		}
#pragma endregion


	private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
                br1 = gcnew SolidBrush(Color::White);
		g->FillRectangle(br1, 0, 0, pictureBox1->Width, pictureBox1->Height);
		pts = gcnew array<Point>(9);
		p = gcnew Pen(Color::Blue, 2);
		p1 = gcnew Pen(Color::Red, 2);
		// цилиндр
		Point pt1 = Point(290, 210);
		Point pt2 = Point(410, 210);
		g->DrawLine(p, pt1, pt2);
		Point pt3 = Point(290, 160);
		Point pt4 = Point(410, 160);
		g->DrawLine(p, pt3, pt4);
		br = gcnew SolidBrush(Color::Black);
		
		br2 = gcnew SolidBrush(Color::Red);
		br3 = gcnew SolidBrush(Color::CadetBlue);
		// катушка
		g->FillEllipse(br, 135, 135, 100, 100);
		// центр
		g->FillEllipse(br1, 180, 180, 10, 10);
		// сегменты
		g->FillPie(br1, 140, 140, 90, 90, 0 - i, 45);
		g->FillPie(br1, 140, 140, 90, 90, 90 - i, 45);
		g->FillPie(br1, 140, 140, 90, 90, 180 - i, 45);
		g->FillPie(br1, 140, 140, 90, 90, 270 - i, 45);
		// поворот
		x2 = 180 + (180 - 230)*cos(-i*3.14 / 180);
		y2 = 180 + (180 - 230)*sin(-i*3.14 / 180);
		// шарнир
		g->DrawEllipse(p1, x2, y2, 10, 10);
		// балка
		g->DrawLine(p1, x2 + 5, y2 + 5, x2 + 160, 185);
		// шарнир
		g->DrawEllipse(p1, x2 + 155, 180, 10, 10);
		// поршень
		g->FillRectangle(br3, x2 + 160, 160, 15, 50);
		// шар
		pts[0] = Point(410, 160);
		pts[4] = Point(610, 185);
		pts[8] = Point(410, 210);
		y = 185;
		yc = y+abs(sin(-i/2*3.14 / 180))*(135-y)-25;
		pts[1] = Point(460, yc);
		yc = y +  abs(sin(-i/2*3.14 / 180))*(235 - y)+25;
		pts[7] = Point(460, yc);
		y = 185;
		yc = y + abs(sin(-i/2*3.14 / 180))*(135 - y) - 25;
		pts[2] = Point(510, yc);
		yc = y + abs(sin(-i/2*3.14 / 180))*(235 - y) + 25;
		pts[6] = Point(510, yc);
		y = 185;
		yc = y + abs(sin(-i/2*3.14 / 180))*(160 - y) - 25;
		pts[3] = Point(560, yc);
		yc = y + abs(sin(-i/2*3.14 / 180))*(210 - y) + 25;
		pts[5] = Point(560, yc);
		
		
		g->FillPolygon(br3, pts);
		i++;
		pictureBox1->Refresh();
	}
	private: System::Void pictureBox1_Click(System::Object^  sender, System::EventArgs^  e) {

	}
	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
		timer1->Start();
		i = 0;
		pictureBox1->Image = gcnew Bitmap(pictureBox1->Width, pictureBox1->Height);
		g = Graphics::FromImage(pictureBox1->Image);
	}
	};
}