简体   繁体   English

C#-在图片框的上方和上方绘制文本

[英]C# - Draw text outside, and above, picturebox

I am currently making a little game where the player is a PictureBox, that can move around. 我目前正在制作一个小游戏,玩家是一个可以移动的PictureBox。 And I am struggling with adding a name-tag above the player (PictureBox). 我正在努力在播放器(PictureBox)上方添加名称标签。 I can't seem to set the X and Y position of the text to be outside the box. 我似乎无法将文本的X和Y位置设置在框外。 It just lands inside. 它只是降落在里面。 I made a picture showing and describing what I want to achieve: 我做了一张图片,展示并描述了我想要实现的目标:

图片

Here is my code to draw the character name. 这是我绘制角色名称的代码。 By the way, my character name is stored in the variable CharacterName.charName 顺便说一句,我的角色名称存储在变量CharacterName.charName中

private void Main_Load(object sender, EventArgs e)
    {
        //Draw character name upon start
        ListToPaint.Add(new WhatToPaint { X = 10, Y = 10, Text = CharacterName.charName });
    }

    private List<WhatToPaint> ListToPaint = new List<WhatToPaint>();
    private class WhatToPaint
    {
        public int X { get; set; }
        public int Y { get; set; }
        public string Text { get; set; }
    }

    private void player_Paint(object sender, PaintEventArgs e)
    {
        //This is the "Paint" properties on my PictureBox, called Player
        e.Graphics.Clear(Color.White);
        foreach (WhatToPaint wp in ListToPaint)
        {
            e.Graphics.DrawString(wp.Text, this.Font, Brushes.Black, wp.X, wp.Y);
        }
    }

If you put the Label in the same container as the PictureBox (not within the pictureBox), you could just use coordinate math to put it (y) pixels above the PictureBox 如果将Label与PictureBox放在同一容器中(不在pictureBox内),则可以使用坐标数学将其放在PictureBox上方(y)像素

For example you could put the Label and Picture box into a transparent Panel. 例如,您可以将“标签和图片”框放入透明面板中。 You could then move the whole panel as a Label-PictureBox unit. 然后,您可以将整个面板作为Label-PictureBox单元移动。 Then the Label and PictureBox would have the same coordinate reference (since they are in the same container). 然后,Label和PictureBox将具有相同的坐标参考(因为它们位于同一容器中)。

To center the Label text (regardless of the text), do something like using the width of the text box to find where the midpoint would be. 要使Label文本居中(无论文本如何),请执行类似操作,例如使用文本框的宽度来查找中点。 Then offset the Label by that midpoint (yet more coordinate math). 然后将Label偏移该中点(还有更多坐标数学)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM