Show transparent label above PictureBox in C# form
In C# forms, when trying to display a transparent label on a PictureBox, users may encounter a gray background instead of the expected transparency effect. This is because PictureBox is not a container control.
Solution 1: Code Implementation
To resolve this issue, modify the form constructor, change the label's parent to a PictureBox and recalculate its position.
<code class="language-csharp">public Form1() { InitializeComponent(); var pos = label1.Parent.PointToScreen(label1.Location); pos = pictureBox1.PointToClient(pos); label1.Parent = pictureBox1; label1.Location = pos; label1.BackColor = Color.Transparent; }</code>
Solution 2: Design-time enhancement
Alternatively, solve the design-time problem by creating a custom class that inherits from ParentControlDesigner.
<code class="language-csharp">using System.ComponentModel; using System.Windows.Forms; using System.Windows.Forms.Design; // 添加对System.Design的引用 [Designer(typeof(ParentControlDesigner))] class PictureContainer : PictureBox {}</code>
Description
Set PictureBox as a container control through the above method, the label will become a child control of PictureBox, and its transparency will be displayed correctly on top of PictureBox.
The above is the detailed content of How to Display a Transparent Label Over a PictureBox in C#?. For more information, please follow other related articles on the PHP Chinese website!