Форум программистов, компьютерный форум, киберфорум
C# Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.82/88: Рейтинг темы: голосов - 88, средняя оценка - 4.82
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290

Точка должна двигаться по окружности, координаты центра и радиус задаются

30.09.2011, 09:25. Показов 18723. Ответов 31
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
точка должна двигаться по окружности,координаты центра и радиус задаются.когда меняю координаты центра ничего не прорисовывается((help
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
{
    public partial class Form1 : Form
    {
        #region функции рисования
 
        private void Circle(Graphics g, int x, int y, int diametr) //рисование окружности 
        {
            g.DrawEllipse(new Pen(Color.Red,3), x, y, diametr, diametr);
        }
 
        private void DrawLine1(Graphics g, int x, int y, int x1, int y1)//рисование тонкой линии 
        {
            g.DrawLine(new Pen(Color.Red),x,y,x1,y1);
        }
 
        private void DrawLine2(Graphics g, int x, int y, int x1, int y1)//рисование толстой линии 
        {
            g.DrawLine(new Pen(Color.Blue, 3), x, y, x1, y1);
        }
 
        #endregion
 
        #region переменные
 
        int x0, y0, счетчик = 0;
        double AB, H;
        double КосФ;
        int Xa, Ya, Xb, Yb, Xc, Yc, Xd, Yd, Xe, Ye, Xm, Ym;
        double[] КосинусФПриВходе = {1,0.99939,0.997564,0.994521,0.990268,0.9848,0.97814,0.97029,0.961261,0.9510565,0.93969,0.927183,0.913545,0.898794,0.88294,
                                     0.866025,0.848048,0.8290375,0.809016,0.78801,0.76604,0.74314,0.71933,0.69465,0.66913,0.64278,0.61566,0.58778,0.55919,0.5,
                                     0.46947,0.43837,0.40673,0.3746,0.34202,0.309016,0.27563,0.24192,0.20791,0.17364,0.13917,0.104528,0.06975,0.034899,0,-0.03489,
                                     -0.06975,-0.104528,-0.13917,-0.17364,-0.20791,-0.24192,-0.27563,-0.309016,-0.34202,-0.3746,-0.40673,-0.43837,-0.46947,-0.5,
                                     -0.55919,-0.58778,-0.61566,-0.64278,-0.66913,-0.69465,-0.71933,-0.74314,-0.76604,-0.78801,-0.809016,-0.8290375,-0.848048,
                                     -0.866025,-0.88294,-0.898794,-0.913545,-0.927183,-0.93969,-0.9510565,-0.961261,-0.97029,-0.97814,-0.9848,-0.990268,-0.994521,
                                     -0.997564,-0.99939,-1,-0.99939,-0.997564,-0.994521,-0.990268,-0.9848,-0.97814,-0.97029,-0.961261,-0.9510565,-0.93969,-0.927183,
                                     -0.913545,-0.898794,-0.88294,-0.866025,-0.848048,-0.8290375,-0.809016,-0.78801,-0.76604,-0.74314,-0.71933,-0.69465,-0.66913,
                                     -0.64278,-0.61566,-0.58778,-0.55919,-0.5,-0.46947,-0.43837,-0.40673,-0.3746,-0.34202,-0.309016,-0.27563,-0.24192,-0.20791,
                                     -0.17364,-0.13917,-0.104528,-0.06975,-0.034899,0,0.03489,0.06975,0.104528,0.13917,0.17364,0.20791,0.24192,0.27563,0.309016,
                                     0.34202,0.3746,0.40673,0.43837,0.46947,0.5,0.55919,0.58778,0.61566,0.64278,0.66913,0.69465,0.71933,0.74314,0.76604,0.78801,
                                     0.809016,0.8290375,0.848048,0.866025,0.88294,0.898794,0.913545,0.927183,0.93969,0.9510565,0.961261,0.97029,0.97814,0.9848,
                                     0.990268,0.994521,0.997564,0.99939};
        
        #endregion
 
        public Form1()
        {
            InitializeComponent();
 
            x0 = pictureBox1.Width / 2;
            y0 = pictureBox1.Height / 2;
        }
 
        private void XbYb()
        {
            double x;
            x = AB * КосФ;
            Xb = (int)x;
            double f=4*Ya*Ya-4*(Xa*Xa+Ya*Ya+Xb*Xb-2*Xa*Xb-AB*AB);
            if (счетчик >= 0 && счетчик <= 89) Yb = (2 * Ya + (int)Math.Sqrt(f)) / 2;
            else Yb = (2 * Ya - (int)Math.Sqrt(f)) / 2;
        }
 
        private void button1_Click(object sender, EventArgs e) //перерисовка поля 1,обновление водных данных 
        {
            double.TryParse(textBox1.Text, out AB);
            int.TryParse(textBox2.Text, out Xa);
            int.TryParse(textBox3.Text, out Ya);
            XbYb();
            pictureBox1.Invalidate();
        }
 
        private void pictureBox1_Paint(object sender, PaintEventArgs e) // invalidate 
        {
            DrawLine1(e.Graphics, 0, pictureBox1.Height/2, pictureBox1.Width, pictureBox1.Height/2);
            DrawLine1(e.Graphics, pictureBox1.Width/2, 0, pictureBox1.Width/2, pictureBox1.Height);
            Circle(e.Graphics, x0 + Xa - 3, y0 - Ya - 3, 6);
            Circle(e.Graphics, x0 + Xb - 3, y0 - Yb - 3, 6);
        }
 
 
        private void button2_Click(object sender, EventArgs e)//запуск таймера 
        {
            timer1.Enabled = true;   
        }
 
        private void button3_Click(object sender, EventArgs e)//остановка таймера 
        {
            timer1.Enabled = false;
        }  
        
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (счетчик == КосинусФПриВходе.Length) счетчик = 0;
            КосФ=КосинусФПриВходе[счетчик];
            XbYb();
            pictureBox1.Invalidate();
            счетчик++;
        }
    }
}
1
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
30.09.2011, 09:25
Ответы с готовыми решениями:

Найти координаты всех вершин правильного многоугольника, зная координаты центра и радиус описанной окружности.
Дан правильный N-угольник с центром в точке (X, Y) и с радиусом описанной окружности R. Найти координаты всех вершин многоугольника. ...

Вывести координаты центра и радиус наибольшей окружности
program record_with5; type coordcent = record x: real; y: real; end; type coordrad = coordcent;

Определить координаты центра и радиус описанной около треугольника окружности
В плоскости задан треугольник координатами своих вершин. Определить координаты центра и радиус описанной около треугольника окружности. Для...

31
Злой няш
 Аватар для I2um1
2136 / 1505 / 565
Регистрация: 05.04.2010
Сообщений: 2,881
08.10.2011, 00:52
Студворк — интернет-сервис помощи студентам
Когда точка A будет находится на 180-ом градусе. Точка B выйдет за B1 - деваться больше не куда.
Не понятно по какому принципу/закону осуществляется это колебание.
Что за формулу вывели?
0
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290
11.10.2011, 21:44  [ТС]
с этим разобралсябуду решать дальше
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void LocationB()
        {
            float sumFloat = (pointA.X - pointC.X) * (pointA.X - pointC.X) + (pointA.Y - pointC.Y) * (pointA.Y - pointC.Y);
            double sumDouble = (double)sumFloat;
            double SqrtSumDouble = Math.Sqrt(sumDouble);
            float SqrtSumFloat = (float)SqrtSumDouble;
            if (SqrtSumFloat > Math.Abs(2 * BCLength) || SqrtSumFloat < 0)
            {
                timer1.Stop();
                MessageBox.Show("Разрыв в точке В");
            }
            else
            {
                float b = (SqrtSumFloat * SqrtSumFloat) / (2 * SqrtSumFloat);
                float a = SqrtSumFloat - b;
                double h_ = BCLength * BCLength - b * b;
                double SqrtH_ = Math.Sqrt(h_);
                float Height = (float)SqrtH_;
                float x = pointA.X + (pointC.X - pointA.X) / (SqrtSumFloat / a);
                float y = pointA.Y + (pointC.Y - pointA.Y) / (SqrtSumFloat / a);
                pointB.X = x - (y - pointC.Y) * Height / b;
                pointB.Y = y + (x - pointC.X) * Height / b;
            }
        }
0
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290
14.10.2011, 14:58  [ТС]
следующий вопрос: "механизм работает",я вычисляю ход рабочего звена, и пока идет вычисление я хочу спрятать панель,на которой идет отрисовка(ну или можно закрыть чем нибудь другим например с текстом "идет рассчет"). как это реализовать? (во время вычислений механизм должен работать(таймер тикать))
0
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290
14.10.2011, 16:12  [ТС]
с этим разобрался...
механизм мой показан на рисунке. для каждой точки у меня должны строиться графики скорости и ускорения..как это лучше реализовать??
может например строить по одному? : пользователь выбирает какой график и для какой точки ему надо, производится расчет и график рисуется на другой Форме?
Миниатюры
Точка должна двигаться по окружности, координаты центра и радиус задаются  
0
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290
23.10.2011, 16:01  [ТС]
с этим тоже разобрался...еще вопрос: есть отрезок, один конец которого "закреплен". второй конец(точка отрезка) будет колебаться(влево вправо двигаться(красный пунктир-траектория)). мне нужно около точки Е этому отрезку построить 2 параллельных...как это сделать
Изображения
 
0
31.10.2011, 22:12  [ТС]

Не по теме:

ни у кого нет никаких мыслей по моему вопросу??((

0
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290
05.11.2011, 18:37  [ТС]
в общем получилась вот такая прога...
Вложения
Тип файла: rar mex.rar (1.02 Мб, 32 просмотров)
0
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290
28.12.2011, 15:44  [ТС]
возник вопрос: а как организовать движение точки по эллипсу?? помогите плиз
0
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290
28.12.2011, 16:39  [ТС]

Не по теме:

опять сам спросил сам ответил)


эллипс

кинул на форму Timer, Panel и 2 textBox'а (1 - ширина траектории, 2 - высота)

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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;
 
namespace pointToEllipse
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        double angle;
 
        int width, height;
        float x, y;
 
        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Interval = 1;
            timer1.Enabled = true;
 
            int.TryParse(textBox1.Text, out width);
            int.TryParse(textBox2.Text, out height);
            x = panel1.Width / 2 + width;
            y = panel1.Height / 2 + height;
            angle = 0;
        }
 
        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics graphics = panel1.CreateGraphics();
 
            graphics.Clear(Color.White);
            graphics.FillEllipse(new SolidBrush(Color.Red), x-4, y-4, 8,8);//точка
            graphics.DrawEllipse(new Pen(Color.Green), panel1.Width / 2 - width/2, panel1.Height / 2 - height/2, width, height);
        }
 
        private void timer1_Tick(object sender, EventArgs e)
        {
            angle+=0.01;
            RunPoint();
            Invalidate();
        }
 
        public void RunPoint()
        {
            x = width / 2 * (float)Math.Cos(angle) + panel1.Width / 2;
            y = height / 2*(float)Math.Sin(angle) + panel1.Height / 2;
        }
 
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            int newWidth,newHeight;
            if (int.TryParse(textBox1.Text, out newWidth)
                && int.TryParse(textBox2.Text, out newHeight))
            {
                width = newWidth;
                height = newHeight;
            }
        }
    }
}
Миниатюры
Точка должна двигаться по окружности, координаты центра и радиус задаются  
0
c#
 Аватар для temich-92
95 / 95 / 27
Регистрация: 25.03.2011
Сообщений: 290
12.01.2012, 12:19  [ТС]
решил переделать программу..чтобы не мигало..рисуется теперь все ок,но столкнулся с проблемой в расчетах.

в этом коде(код в timer_Tick):
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
if (calcDWork)
            {
                workPointDOut.Text = "идет расчет хода \n выходного звена...";
                
 
                if (!pointMov.circ)
                {
                    workPointDCalkList.Add(pointD);
 
                    for (int i = 0; i < workPointDCalkList.Count; i++)
                    {
                        tempCalc.Add(workPointDCalkList[i].X);
                    }
 
                    tempCalc.Sort();
 
                    pointDMinX.X = tempCalc[0]; pointDMinX.Y = pointD.Y;
                    pointDMaxX.X = tempCalc[tempCalc.Count - 1]; pointDMaxX.Y = pointD.Y;
 
                    standD.UpdatePoints(new PointF(pointDMinX.X, pointDMinX.Y), new PointF(pointD.X, pointDMaxX.Y));
                }
                else
                {
                    calcDWork = false;
                    workPointDCalkList.Clear();
                }
            }
C#
1
workPointDCalkList.Add(pointD);
в лист точек (класс точек мой) забиваю с каждым тиком точку, для которой веду расчет.
C#
1
2
3
4
5
6
for (int i = 0; i < workPointDCalkList.Count; i++)
                    {
                        tempCalc.Add(workPointDCalkList[i].X);
                    }
 
                    tempCalc.Sort();
в List<float> забиваю X этих точек и лист сортирую, а потом беру максимальный и минимальный элементы (первый и последний) и рисую то что мне нужно (опору), но вот в чем загвоздка - рисуется только когда точка идет вправо..не понимаю почему


весь код:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
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;
 
namespace СтрогальныйСтанок
{
    public partial class Form1 : Form
    {
        Panel panel;
        Button startButton;
        Button stopButton;
 
        TextBox[] inputTextBox;
        Label[] inputLabel;
        int countInputControls = 8;
 
        Button updateButton;
 
        Label workPointDOut;        
 
        Pen pen;
 
        Timer timer;
 
        Graphics graphics;
        BufferedGraphics bufferedGraphics;
        BufferedGraphicsContext bufferedGraphicsContext;
 
        float ABLenght, MDLenght, height;
 
        _PointMov pointMov;
        _Point
            pointA,
            pointE,
            pointC,
            pointB,
            pointM,
            pointD;
 
        _Line 
            lineEA,
            lineAB,
            lineBC,
            lineBM,
            lineMD;
 
        _Stand standE;
        _Stand standD;
 
        List<string> inputLabelText = new List<string>() { "Ex", "Ey", "Cx", "Cy", "AE", "AB=BC=BM", "MD", "H" };
        List<float> inputTextBoxText = new List<float>() { 110, 60, 85, 80, 12, 25, 50, 45 };
        bool formShow;
 
        List<_Point> workPointDCalkList;
        List<float> tempCalc;
        _Point pointDMinX, pointDMaxX;
        bool calcDWork;
 
        _Point counterPoint;
 
        public Form1()
        {
            InitializeComponent();
            
            ClientSize = new Size(800, 500);
            MinimumSize = new System.Drawing.Size(640, 480);
 
            StartPosition = FormStartPosition.CenterScreen;
 
            #region создаем контролы формы
 
            panel = new Panel();
            panel.Location = new Point(2, 2);
            panel.Height = Height - 2;
            panel.Width = Width - 200;
            panel.BackColor = Color.White;
            Controls.Add(panel);
 
            startButton = new Button();
            startButton.Size = new Size(100, 25);
            startButton.Location = new Point(panel.Width + 2 + (Width - panel.Width) / 2 - startButton.Width / 2, 10);
            startButton.Text = "старт";
            startButton.Click += new EventHandler(start_Click);
            Controls.Add(startButton);
 
            stopButton = new Button();
            stopButton.Size = new Size(100, 25);
            stopButton.Location = new Point(panel.Width + 2 + (Width - panel.Width) / 2 - startButton.Width / 2, 45);
            stopButton.Text = "стоп";
            stopButton.Click += new EventHandler(stop_Click);
            Controls.Add(stopButton);
 
            inputTextBox = new TextBox[countInputControls];
            inputLabel = new Label[countInputControls];
 
            int xTextBox = startButton.Location.X + startButton.Width / 2,
                xLabel = startButton.Location.X-10,
                y = stopButton.Bottom + 10;
 
            for (int i = 0; i < countInputControls; i++)
            {
                TextBox tb = new TextBox();
                tb.Size = new Size(50, 25);
                tb.Location = new Point(xTextBox, y);
                tb.Text = inputTextBoxText[i].ToString();
                
                Label lbl = new Label();
                lbl.AutoSize = true;
                lbl.Text = inputLabelText[i];
                lbl.Location = new Point(xLabel, y);
                
                inputTextBox[i] = tb;
                inputLabel[i] = lbl;
 
                y += 35;
            }
            for (int i = 0; i < countInputControls; i++)
            {
                Controls.Add(inputTextBox[i]);
                Controls.Add(inputLabel[i]);
            }
 
            updateButton = new Button();
            updateButton.Size = new Size(100, 25);
            updateButton.Location = new Point(panel.Width + 2 + (Width - panel.Width) / 2 - updateButton.Width / 2, y);
            updateButton.Text = "обновить";
            updateButton.Click += new EventHandler(update_Click);
            Controls.Add(updateButton);
 
            y += 35;
 
            workPointDOut = new Label();
            workPointDOut.AutoSize = true;
            workPointDOut.TextAlign = ContentAlignment.MiddleCenter;
            workPointDOut.Text = "идет расчет хода \n выходного звена...";
            workPointDOut.Location = new Point(panel.Width + 2 + (Width - panel.Width) / 2 - workPointDOut.Width / 2, y);
            Controls.Add(workPointDOut);
 
            #endregion
 
            pen = new Pen(Color.Red);
 
            timer = new Timer();
            timer.Interval = 1;
            timer.Tick += new EventHandler(timer_Tick);
 
            InitializeGraphics();
 
            pointMov = new _PointMov(0,0, 50, 2, 0.01f, new SolidBrush(Color.Red));
            pointA = new _Point(pointMov.X, pointMov.Y, 0, new SolidBrush(Color.White));
 
            pointE = new _Point(0, 0, 2, new SolidBrush(Color.Red));
            pointC = new _Point(0, 0, 2, new SolidBrush(Color.Red));
            pointB = new _Point(0, 0, 2, new SolidBrush(Color.Green));
            pointM = new _Point(0, 0, 2, new SolidBrush(Color.Green));
            pointD = new _Point(0, 0, 2, new SolidBrush(Color.Green));
 
            lineEA = new _Line(new Pen(Color.Red, 0.5f));
            lineAB = new _Line(new Pen(Color.Green, 0.5f));
            lineBC = new _Line(new Pen(Color.Green, 0.5f));
            lineBM = new _Line(new Pen(Color.Green, 0.5f));
            lineMD = new _Line(new Pen(Color.Green, 0.5f));
 
            //standE = new _Stand(new Point((int)pointE.X, (int)pointE.Y), new Pen(Color.Black, 1));
            workPointDCalkList = new List<_Point>();
            tempCalc = new List<float>();
 
            pointDMinX = new _Point(0, 0, 2, new SolidBrush(Color.Red));
            pointDMaxX = new _Point(0, 0, 2, new SolidBrush(Color.Red));
 
            formShow = true;
        }
 
        private void timer_Tick(object sender,EventArgs e)
        {
            pointMov.CenterX = pointE.X;
            pointMov.CenterY = pointE.Y;
 
            pointMov.Mov();
            pointA.X = pointMov.X;
            pointA.Y = pointMov.Y;
 
            LocationB();
            LocationM();
            LocationD();
 
            lineEA.NewPoints(pointE, pointA);
            lineAB.NewPoints(pointA, pointB);
            lineBC.NewPoints(pointB, pointC);
            lineBM.NewPoints(pointB, pointM);
            lineMD.NewPoints(pointM, pointD);
 
            //*************************************************************************************
            //вот рассчеты
 
            if (calcDWork)
            {
                workPointDOut.Text = "идет расчет хода \n выходного звена...";
                
 
                if (!pointMov.circ)
                {
                    workPointDCalkList.Add(pointD);
 
                    for (int i = 0; i < workPointDCalkList.Count; i++)
                    {
                        tempCalc.Add(workPointDCalkList[i].X);
                    }
 
                    tempCalc.Sort();
 
                    pointDMinX.X = tempCalc[0]; pointDMinX.Y = pointD.Y;
                    pointDMaxX.X = tempCalc[tempCalc.Count - 1]; pointDMaxX.Y = pointD.Y;
 
                    standD.UpdatePoints(new PointF(pointDMinX.X, pointDMinX.Y), new PointF(pointD.X, pointDMaxX.Y));
                }
                else
                {
                    calcDWork = false;
                    workPointDCalkList.Clear();
                }
            }
 
            //**************************************************************************************************
 
            DrawToBuffer();
        }
 
        private void InitializeGraphics()
        {
            graphics = panel.CreateGraphics();
            bufferedGraphicsContext = new BufferedGraphicsContext();
            bufferedGraphics = bufferedGraphicsContext.Allocate(graphics, new Rectangle(0, 0, panel.Width, panel.Height));
            bufferedGraphics.Graphics.PageUnit = GraphicsUnit.Millimeter;
        }
 
        private void DrawToBuffer()
        {
            graphics.PageUnit = GraphicsUnit.Millimeter;
            bufferedGraphics.Graphics.Clear(Color.White);
 
            pointMov.Draw(bufferedGraphics.Graphics);
            pointE.Draw(bufferedGraphics.Graphics);
            pointC.Draw(bufferedGraphics.Graphics);
            pointB.Draw(bufferedGraphics.Graphics);
            pointM.Draw(bufferedGraphics.Graphics);
            pointD.Draw(bufferedGraphics.Graphics);
 
            lineEA.Draw(bufferedGraphics.Graphics);
            lineAB.Draw(bufferedGraphics.Graphics);
            lineBC.Draw(bufferedGraphics.Graphics);
            lineBM.Draw(bufferedGraphics.Graphics);
            lineMD.Draw(bufferedGraphics.Graphics);
 
            standE.Draw(bufferedGraphics.Graphics);
            standD.Draw(bufferedGraphics.Graphics);
 
            bufferedGraphics.Render();
        }
 
        public void start_Click(object sender,EventArgs e)
        {
            updateButton.PerformClick();
            timer.Start();
        }
 
        public void stop_Click(object sender, EventArgs e) 
        {
            timer.Stop();
        }
 
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
            {
                timer.Stop();
            }
 
            if (formShow && timer.Enabled)
            {
                panel.Height = Height - 2;
                panel.Width = Width - 200;
 
                bufferedGraphics = bufferedGraphicsContext.Allocate(graphics, new Rectangle(0, 0, panel.Width, panel.Height));
                bufferedGraphics.Graphics.PageUnit = GraphicsUnit.Millimeter;
 
                startButton.Location = new Point(panel.Width + 2 + (Width - panel.Width) / 2 - startButton.Width / 2, 50);
                stopButton.Location = new Point(panel.Width + 2 + (Width - panel.Width) / 2 - startButton.Width / 2, 75);
 
                int xTextBox = startButton.Location.X + startButton.Width / 2,
                    xLabel = startButton.Location.X - 10,
                    y = stopButton.Bottom + 10;
 
                for (int i = 0; i < countInputControls; i++)
                {
                    inputTextBox[i].Location = new Point(xTextBox, y);
                    inputLabel[i].Location = new Point(xLabel, y);
 
                    y += 35;
                }
 
                updateButton.Location = new Point(panel.Width + 2 + (Width - panel.Width) / 2 - updateButton.Width / 2, y);
            }
        }
 
        public void update_Click(object sender,EventArgs e)
        {
            float Ex, Ey, Cx, Cy, movRadius;
            if (float.TryParse(inputTextBox[0].Text, out Ex)
                && float.TryParse(inputTextBox[1].Text, out Ey)
                && float.TryParse(inputTextBox[2].Text, out Cx)
                && float.TryParse(inputTextBox[3].Text, out Cy)
                && float.TryParse(inputTextBox[4].Text, out movRadius)
                && float.TryParse(inputTextBox[5].Text, out ABLenght)
                && float.TryParse(inputTextBox[6].Text, out MDLenght)
                && float.TryParse(inputTextBox[7].Text, out height))
            {
                pointE.X = Ex;
                pointE.Y = Ey;
                pointC.X = Cx;
                pointC.Y = Cy;
                pointMov.Radius = movRadius;
 
                standE = new _Stand(pointE, new Pen(Color.Black, 0.5f));
                standD = new _Stand(pointDMinX, pointDMaxX, true, new Pen(Color.Black, 0.5f));
 
                calcDWork = true;
                pointMov.ResetCirc();
            }
            else
            {
                timer.Stop();
                MessageBox.Show("ошибка ввода", "ошибка");
            }
        }
 
        #region расчет координат движущихся точек
 
        /// <summary>
        /// расчет координат точки B
        /// </summary>
        void LocationB() 
        {
            float sumFloat = (pointA.X - pointC.X) * (pointA.X - pointC.X) + (pointA.Y - pointC.Y) * (pointA.Y - pointC.Y);
            double sumDouble = (double)sumFloat;
            double SqrtSumDouble = Math.Sqrt(sumDouble);
            float SqrtSumFloat = (float)SqrtSumDouble;
 
            if (SqrtSumFloat > Math.Abs(2 * ABLenght) || SqrtSumFloat < 0)
            {
                timer.Stop();
                MessageBox.Show("Разрыв в точке В");
            }
            else
            {
                float b = (SqrtSumFloat * SqrtSumFloat) / (2 * SqrtSumFloat);
                float a = SqrtSumFloat - b;
                double h_ = ABLenght * ABLenght - b * b;
                double SqrtH_ = Math.Sqrt(h_);
                float Height = (float)SqrtH_;
                float x = pointA.X + (pointC.X - pointA.X) / (SqrtSumFloat / a);
                float y = pointA.Y + (pointC.Y - pointA.Y) / (SqrtSumFloat / a);
                pointB.X = x + (y - pointC.Y) * Height / b;
                pointB.Y = y - (x - pointC.X) * Height / b;
            }
        }
 
        /// <summary>
        /// расчет координат точки M
        /// </summary>
        void LocationM()
        {
            //нахождение длины отрезка AM(будущий радиус окружности с центром в точке А)
            float AMLenght;
            double SqrAMDouble = 2.10467f * ABLenght * ABLenght;
            double AM = Math.Sqrt(SqrAMDouble);
            AMLenght = (float)AM;
 
            float sumFloat = (pointA.X - pointB.X) * (pointA.X - pointB.X) + (pointA.Y - pointB.Y) * (pointA.Y - pointB.Y);
            double sumDouble = (double)sumFloat;
            double SqrtSumDouble = Math.Sqrt(sumDouble);
            float SqrtSumFloat = (float)SqrtSumDouble;
            float b = (ABLenght * ABLenght - AMLenght * AMLenght + SqrtSumFloat * SqrtSumFloat) / (2 * SqrtSumFloat);
            float a = SqrtSumFloat - b;
            double h_ = ABLenght * ABLenght - b * b;
            double SqrtH_ = Math.Sqrt(h_);
            float Height = (float)SqrtH_;
            float x = pointA.X + (pointB.X - pointA.X) / (SqrtSumFloat / a);
            float y = pointA.Y + (pointB.Y - pointA.Y) / (SqrtSumFloat / a);
            pointM.X = x + (y - pointB.Y) * Height / b;
            pointM.Y = y - (x - pointB.X) * Height / b;
        }
 
        /// <summary>
        /// расчет координат точки D
        /// </summary>
        void LocationD()
        {
            pointD.Y = pointC.Y - height;
            float b = pointD.Y;
            if (b < pointM.Y - MDLenght && b > pointM.Y + MDLenght)
            {
                timer.Stop();
                MessageBox.Show("разрыв в точке D");
            }
            else
            {
                float c = -MDLenght * MDLenght;
                double Discrim = -4 * c;
                double SqrtDiscrimDouble = Math.Sqrt(Discrim);
                float SqrtDiscrimFloat = (float)SqrtDiscrimDouble;
                if (Discrim <= 0)
                {
                    timer.Stop();
                    MessageBox.Show("разрыв в точке D");
                }
                else
                {
                    float k = 0;
                    float a = 1 + k * k;
                    float bb = -2 * pointM.X + 2 * k * b - 2 * k * pointM.Y;
                    float cc = pointM.X * pointM.X + b * b - 2 * b * pointM.Y + pointM.Y * pointM.Y - MDLenght * MDLenght;
                    double Discr = bb * bb - 4 * a * cc;
                    double SqrtDiscrDouble = Math.Sqrt(Discr);
                    float SqrtDiscrFloat = (float)SqrtDiscrDouble;
                    pointD.X = (-bb - SqrtDiscrFloat) / (2 * a);
                    pointD.Y = k * pointD.X + b;
                }
            }
        }
 
        #endregion
    }
 
    #region классы
 
    public class _PointMov 
    {
        float x, y;
        float centerX, centerY, radius;
 
        Brush brush;
 
        float angle;
 
        float velocity;
 
        int size;
 
        public bool circ;
 
        /// <summary>
        /// контруктор
        /// </summary>
        /// <param name="centerX"> координата X центра окружности, по которой движется точка </param>
        /// <param name="centerY"> координата Y центра окружности, по которой движется точка </param>
        /// <param name="radius"> радиус окружности, по которой движется точка </param>
        /// <param name="size"> высота точки = ширина точки = size </param>
        /// <param name="velocity"> скорость точки </param>
        /// <param name="brush"> кисть, которой рисуется точка </param>
        public _PointMov(int centerX, int centerY, int radius, int size,float velocity, Brush brush)
        {
            this.centerX = centerX;
            this.centerY = centerY;
            this.radius = radius;
            this.velocity = velocity;
            this.brush = brush;
 
            this.size = size;
        }
 
        /// <summary>
        /// координата X центра окружности, по которой движется точка
        /// </summary>
        public float CenterX
        {
            get { return centerX; }
            set
            {
                centerX = value;
                x = (float)Math.Cos(angle) * radius + centerY;
            }
        }
 
        /// <summary>
        /// координата Y центра окружности, по которой движется точка
        /// </summary>
        public float CenterY
        {
            get { return centerY; }
            set
            {
                centerY = value;
                y = (float)Math.Sin(angle) * radius + centerY;
            }
        }
 
        /// <summary>
        /// радиус окружности, по которой движется точка
        /// </summary>
        public float Radius
        {
            get { return radius; }
            set { radius = value; }
        }
 
        /// <summary>
        /// кисть, которой рисуется точка
        /// </summary>
        public Brush Brush
        {
            get { return brush; }
            set { brush = value; }
        }
 
        /// <summary>
        /// текущий угол точки
        /// </summary>
        public float Angle
        {
            get { return angle; }
            set { angle = value; }
        }
 
        /// <summary>
        /// координата X точки
        /// </summary>
        public float X
        {
            get { return x; }
        }
 
        /// <summary>
        /// координата Y точки
        /// </summary>
        public float Y
        {
            get { return y; }
        }
 
        /// <summary>
        /// угловая скорость точки
        /// </summary>
        public float Velocity
        {
            get { return velocity; }
            set { velocity = value; }
        }
 
        /// <summary>
        /// шаг точки
        /// </summary>
        public void Mov()
        {
            angle += velocity;
 
            if (angle > 2f * Math.PI)
            {
                angle -= 2f * (float)Math.PI;
                circ = true;
                
            }
            x = (float)Math.Cos(angle) * radius + centerX;
            y = (float)Math.Sin(angle) * radius + centerY;
        }
 
        /// <summary>
        /// сбрасываем флаг оборота точки
        /// </summary>
        public void ResetCirc()
        {
            circ = false;
        }
 
        /// <summary>
        /// рисование точки
        /// </summary>
        /// <param name="graphics"> графический объект </param>
        public void Draw(Graphics graphics)
        {
            graphics.FillEllipse(brush, x - size / 2, y - size / 2, size, size);
        }
    }
 
    public class _Point
    {
        float x, y;
        int size;
 
        Brush brush;
 
        /// <summary>
        /// конструктор
        /// </summary>
        /// <param name="x"> координата X точки </param>
        /// <param name="y"> координата Y точки </param>
        /// <param name="size"> ширина точки = высота точки = size </param>
        /// <param name="brush"> кисть, которой рисуется точка </param>
        public _Point(float x, float y,int size, Brush brush)
        {
            this.x = x;
            this.y = y;
            this.size = size;
            this.brush = brush;
        }
 
        /// <summary>
        /// координата X точки
        /// </summary>
        public float X
        {
            get { return x; }
            set { x = value; }
        }
 
        /// <summary>
        /// координата Y точки
        /// </summary>
        public float Y
        {
            get { return y; }
            set { y = value; }
        }
 
        /// <summary>
        /// рисуем точку
        /// </summary>
        /// <param name="graphics"> графический объект </param>
        public void Draw(Graphics graphics)
        {
            graphics.FillEllipse(brush, x - size / 2, y - size / 2, size, size);
        }
    }
 
    public class _Line
    {
        Pen pen;
 
        float x1, y1, x2, y2;
 
        _Point point1, point2;
 
        /// <summary>
        /// конструктор
        /// </summary>
        /// <param name="pen"> перо, которым рисуется точка </param>
        public _Line(Pen pen)
        {
            this.pen = pen;
        }
 
        /// <summary>
        /// перо, которым рисуется линия
        /// </summary>
        public Pen MyPen
        {
            get { return pen; }
            set { pen = value; }
        }
 
        /// <summary>
        /// обновление точек???
        /// </summary>
        /// <param name="point1"> точка 1 </param>
        /// <param name="point2"> точка 2 </param>
        public void NewPoints(_Point point1,_Point point2)
        {
            this.point1 = point1;
            this.point2 = point2;
        }
 
        /// <summary>
        /// рисуем линию
        /// </summary>
        /// <param name="graphics"> графический объект </param>
        public void Draw(Graphics graphics)
        {
            graphics.DrawLine(pen, point1.X, point1.Y, point2.X, point2.Y);
        }
    }
 
    public class _Stand
    {
        Pen pen;
 
        PointF point1, point2;
 
        bool twoPoints;
 
        bool goriz;
 
        PointF[] triangle;
 
        /// <summary>
        /// конструктор
        /// </summary>
        /// <param name="point"> точка опоры </param>
        /// <param name="pen"> перо, которым рисуется опора </param>
        public _Stand(_Point point,Pen pen)
        {
            this.point1 = new PointF(point.X, point.Y);
            this.pen = pen;
 
            triangle = new PointF[4] { new PointF(point.X, point.Y), new PointF(point.X + 2.5f, point.Y + 2.5f), new PointF(point.X - 2.5f, point.Y + 2.5f), new PointF(point.X, point.Y) };
        }
 
        /// <summary>
        /// конструктор
        /// </summary>
        /// <param name="point1"> точка опоры 1 </param>
        /// <param name="point2"> точка опоры 2 </param>
        /// <param name="pen"> перо, которым рисуется опора </param>
        public _Stand(_Point point1, _Point point2,bool goriz, Pen pen)
        {
            this.point1 = new PointF(point1.X, point1.Y);
            this.point2 = new PointF(point2.X, point2.Y);
            this.pen = pen;
 
            this.goriz = goriz;
 
            twoPoints = true;
        }
 
        /// <summary>
        /// обновление параметров для опоры из 2х точек
        /// </summary>
        /// <param name="point1"> точка 1 </param>
        /// <param name="point2"> точка 2 </param>
        public void UpdatePoints(PointF point1,PointF point2)
        {
            this.point1 = point1;
            this.point2 = point2;
        }
 
        /// <summary>
        /// рисует опору
        /// </summary>
        /// <param name="graphics"> графический объект </param>
        public void Draw(Graphics graphics)
        {
            if (twoPoints)
            {
                if (goriz)
                {
                    graphics.DrawLine(pen, point1.X, point1.Y - 4f, point2.X, point2.Y - 4f);
                    graphics.DrawLine(pen, point1.X, point1.Y + 4f, point2.X, point2.Y + 4f);
                }
                else
                {
                    graphics.DrawLine(pen, point1.X - 4f, point1.Y, point2.X - 4f, point2.Y);
                    graphics.DrawLine(pen, point1.X + 4f, point1.Y, point2.X + 4f, point2.Y);
                }
            }
            else
            {
                graphics.DrawLines(pen, triangle);
                graphics.DrawLine(pen, point1.X - 3.5f, point1.Y + 2.5f, point1.X + 3.5f, point1.Y + 2.5f);
                int countLines = 7;
 
                float x = point1.X - 3.5f, y1 = point1.Y + 4.5f, y2 = point1.Y + 2.5f;
 
                for (int i = 0; i < countLines; i++)
                {
                    graphics.DrawLine(pen, x, y1, x + 0.5f, y2);
                    x += 1f;
                }
            }
        }
    }
 
    #endregion
}


Добавлено через 1 час 56 минут
Цитата Сообщение от temich-92 Посмотреть сообщение
workPointDCalkList.Add(pointD);
for (int i = 0; i < workPointDCalkList.Count; i++)
* * * * * * * * * * {
* * * * * * * * * * * * tempCalc.Add(workPointDCalkList[i].X);
* * * * * * * * * * }
зря делал..нужно было просто
C#
1
tempCalc.Add(pointD.X);
и еще накосячил
C#
1
new PointF(pointD.X, pointDMaxX.Y)
а надо
C#
1
new PointF(pointDMaxX.X, pointDMaxX.Y)
0
0 / 0 / 0
Регистрация: 25.02.2012
Сообщений: 10
28.05.2012, 20:44
а как изменится код,если необходимо осуществить движение не точки,а прямоугольника.
не получается что-то дороботать свою старую программу,в которой необходимо похожее движение.
вот что есть,подскажите,как исправить,пожалуйста
0
0 / 0 / 0
Регистрация: 23.12.2021
Сообщений: 6
29.07.2022, 22:22
Как изменить движения против часовой стрелке?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
29.07.2022, 22:22

Составить уравнение плоскости и найти координаты центра и радиус окружности
Дано уравнение сферы S. а) Составить уравнение плоскости,...

Даны координаты центра круга и его радиус, а также координаты точки. Лежит ли эта точка внутри круга?
Даны координаты центра круга и его радиус, а также координаты точки. Лежит ли эта точка внутри круга?

Вывести на экран N окружностей (координаты центра, цвет, радиус окружности генерируются случайным образом)
Помогите с контрольной: Вывести на экран N окружностей (координаты центра, цвет, радиус окружности генерируются случайным образом). (Free...

Как получить координаты центра и радиус окружности, которая вписана в первую четверть другой?
Как получить координаты центра и радиус окружности, которая вписана в первую четверть другой окружности?

Найти радиус и координаты центра вписанной в тетраэдр сферы, если известны координаты вершин тетраэдра
Хотелось бы узнать как решить эту задачу. Предполагаемое решение:


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
32
Ответ Создать тему
Новые блоги и статьи
Нейтральные знания, чистый код - бла-бла-бла-бла, на самом деле кликбейт и самореклама, плагиат, и вот почему
Hrethgir 27.07.2026
То-есть отклонение такой публикации говорит само за себя, и пусть только возьмут на вооружение после отклонения публикации - это будет чистейшим актом плагиата. Отклонял Хабр. Дословно, отклонённая. . .
тв 16 бой ии
anaschu 27.07.2026
Великий Перелом ИИ: Как уравнения ОДУ Radau дожали цензурные фильтры Алисы Фиксируем в мемофонде Теории Всего беспрецедентный факт в истории ИИ-зондирования. В затяжном многораундовом. . .
мв 15. непроверенное, возможно, глюк
anaschu 27.07.2026
НАУЧНО-АНАЛИТИЧЕСКИЙ ОТЧЕТ. РАЗДЕЛ 1. 1: «НАУКА» (РАСШИРЕННАЯ СТЕХИОМЕТРИЧЕСКАЯ И ГЕНЕТИЧЕСКАЯ ВЕРСИЯ)Тема: Теоретическое обоснование инвариантности 19-мерного тензорного ядра непрерывных ОДУ и. . .
Очистка реквизитов и табличных частей документа при копировании (вариант 2)
Maks 26.07.2026
Алгоритм из решения ниже разработан на примере нетипового документа "ЗаявкаНаРаботу", разработанного в КА2. Задача: Заменить алгоритм запрета копирования документов для сотрудников с ролью "Стажер",. . .
Доктрина интенционального знания - Доктрина для портала "Срез".
Hrethgir 25.07.2026
Может найдётся кто захочет оценить доктрину. . . Написания правил участия для меня роскошь, требующая лимита времени, поэтому все сообщения не прошедшие модерацию будут видны только участникам портала,. . .
сукцессия 44. Решил подать на припринт в межународные сервисы препринтов. Но нужно одобрение от ученых
anaschu 25.07.2026
Английский вариант. Пока кто то не одобрит мою личность, мне не получиться это опубликовать на препринте. Но заявку на публикацию статьи я сегодня подам.
сукцессия 43. Вторая научная статья за месяц- прайминг и гатгил
anaschu 25.07.2026
две стороны одной монеты
Более приземисто - Эстафету хвоста в .cdl (деревья эстафеты в сад).
Hrethgir 24.07.2026
В будущем, после написания блока инверсии обхода дерева (эстафеты хвоста), я планирую вернуться к нашему прошлому разговору о том, обладают ли знания целеполаганием. Тогда я пришел к выводу, что. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru