Я относительно новичок в C# и Winform. Я пытаюсь поиграть, нарисовав на панели заданное количество прямоугольников разной высоты с учетом значения, введенного пользователем через трекбар. Я могу успешно рисовать прямоугольники, однако мне также нужна возможность рисовать другие объекты на панели без использования события рисования.
public partial class UCQuickSort : UserControl
{
private DisplayRectangles displayRecs;
private int numRectangles;
private bool shouldDraw;
public UCQuickSort()
{
InitializeComponent();
//this.Resize += Redraw_Resize;
displayRecs = new DisplayRectangles(qsGraphPanel);
this.numRectangles = 0;
this.shouldDraw = false;
}
//private void Redraw_Resize(object sender, EventArgs e) {
// Invalidate();
//}
private void UCQuickSort_Load(object sender, EventArgs e)
{
//qsGraphPanel.BackColor = Color.FromArgb(235, 0, 0, 0);
}
private void setNumberOfRectangles() {
int trackBarValue = sizeInput.Value;
switch (trackBarValue)
{
case 0:
numRectangles = 10;
break;
case 1:
numRectangles = 50;
break;
case 2:
numRectangles = 100;
break;
case 3:
numRectangles = 250;
break;
case 4:
numRectangles = 500;
break;
case 5:
numRectangles = 1000;
break;
}
displayRecs.NumRectangles = numRectangles;
}
private void qsGraphPanel_Paint(object sender, PaintEventArgs e) {
Graphics graphics = qsGraphPanel.CreateGraphics();
displayRecs.Graphics = graphics;
if (shouldDraw) displayRecs.generateRectangles();
shouldDraw = true;
}
private void sizeInput_ValueChanged(object sender, EventArgs e)
{
setNumberOfRectangles();
// Display rectangles
displayRecs.populateRectangles();
qsGraphPanel.Invalidate(true);
}
private void testBtn_Click(object sender, EventArgs e)
{
displayRecs.test();
}
}
public class DisplayRectangles : Form
{
private int[] rectangleHeights;
private int numRectangles;
private Panel panel; // Current panel to paint on
private Random rnd;
private Graphics graphics;
public DisplayRectangles(Panel panel) {
this.panel = panel;
this.graphics = this.panel.CreateGraphics();
this.numRectangles = 10;
this.rnd = new Random();
}
// Getter, Setter function for numRectangles
public int NumRectangles {
get { return numRectangles; }
set {
numRectangles = value;
rectangleHeights = new int[numRectangles];
}
}
public Graphics Graphics {
set {
graphics = value;
}
}
// Populate Rectangles arr with random height values
public void populateRectangles() {
Console.WriteLine("Panel height: " + panel.Height);
for (int i = 0; i < numRectangles; i++) {
rectangleHeights = rnd.Next(0, panel.Height);
}
}
// Display all rectangles on panel
public void generateRectangles() {
Brush fillBrush = Brushes.White;
int width = this.panel.Width/numRectangles; // Width is proportional to numRectangles and panel width
for (int i = 0; i < numRectangles; i++) {
int xPos = i * width;
int yPos = this.panel.Height - rectangleHeights;
int height = rectangleHeights;
//g.FillRectangle(fillBrush, new Rectangle(xPos, yPos, width, height));
graphics.FillRectangle(fillBrush, new Rectangle(xPos, yPos, width, height));
}
}
public void test()
{
Brush myBrush = Brushes.Red;
graphics.FillRectangle(myBrush, new Rectangle(0, 0, 100, 100));
}
}
Я попытался сохранить экземпляр объекта Graphics в своем классе отображения, но нужный мне дополнительный объект не рисуется при нажатии кнопки проверки. Есть какие-нибудь подсказки, как мне это сделать, не проходя через событие рисования?
private void qsGraphPanel_Paint(object sender, PaintEventArgs e) {
Graphics graphics = qsGraphPanel.CreateGraphics();
displayRecs.Graphics = graphics;
if (shouldDraw) displayRecs.generateRectangles();
shouldDraw = true;
}
public void test()
{
Brush myBrush = Brushes.Red;
graphics.FillRectangle(myBrush, new Rectangle(0, 0, 100, 100));
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... aint-event
Картина вне события Paint ⇐ C#
Место общения программистов C#
1 сообщение
• Страница 1 из 1
Anonymous
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...