I have a custom Control
:
public class Temp : Control
{
public Temp(Color col, int x, int y)
{
Size = new Size(x + 10, y + 10);
this.x = x;
this.y = y;
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
BackColor = col;
}
int x, y;
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (var p = new Pen(Color.Black, 3))
{
e.Graphics.DrawLine(p, new Point(10, 10), new Point(x, y));
}
}
}
And from the Load
event of my Form
I add two of these control to the Control
s of a Panel
I added as the only control of my Form:
panel1.Controls.Add(new Temp(Color.Red, 50, 50));
panel1.Controls.Add(new Temp(Color.Violet, 10, 100));
This is the output:
As you can see the first control cover the second one, while I'd want to display only the two lines, where the controls background color is transparent.
Note that using a transparent BackColor doesn't work:
panel1.Controls.Add(new Temp(Color.Transparent, 50, 50));
panel1.Controls.Add(new Temp(Color.Violet, 10, 100));
And this is the output:
How can I solve this problem? That is, display only (and completely) both my lines?
Instead of Inheriting from Control, create two points in your custom class. Sample code given below
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace SOWinForm
{
public partial class Form1 : Form
{
List<Line> lines;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
lines = new List<Line>();
lines.Add(new Line(){ StartPoint = new Point(10,10), EndPoint = new Point(10,100)});
lines.Add(new Line() { StartPoint = new Point(10, 10), EndPoint = new Point(50, 50) });
}
protected override void OnPaint(PaintEventArgs e)
{
foreach (var line in lines)
{
using (var p = new Pen(Color.Black, 3))
{
e.Graphics.DrawLine(p, line.StartPoint, line.EndPoint);
}
}
}
}
public class Line
{
public Point StartPoint {get;set;}
public Point EndPoint { get; set; }
//Add Custom Properties
}
}