C# 如何在绘制的圆中放置图像

C# 如何在绘制的圆中放置图像,c#,C#,我画了一个圆圈: int playerwidth = 40; int playerheight = 40; int xPosp = 0; int yPosp = 0; System.Drawing.SolidBrush pen1 = new System.Drawing.SolidBrush(System.Drawing.Color.White); e.Graphics.FillEllipse(pen1, xPosp, yPosp, playerwidth, playerheight);

我画了一个圆圈:

int playerwidth = 40; 
int playerheight = 40; 
int xPosp = 0;
int yPosp = 0;


System.Drawing.SolidBrush pen1 = new System.Drawing.SolidBrush(System.Drawing.Color.White);
e.Graphics.FillEllipse(pen1, xPosp, yPosp, playerwidth, playerheight);

我的资源中有一个图像,如何将图像放置在圆圈中。

调整要放置在圆圈中的图片的大小,使其适合圆圈,然后向表单中添加一个
PictureBox
,并将要显示的图片添加到
PictureBox
,设置其位置,使其位于圆的中心,如下所示:

编辑: 只需在表单中添加一个
PictureBox
,并将其放置在任意位置,此代码就可以工作了

private static void DrawInEllipse(PictureBox picBox, Image img, Rectangle rect)
{
    picBox.Width = rect.Width - (int)(rect.Width*0.3f);
    picBox.Height = rect.Height - (int)(rect.Width * 0.3f);        

    picBox.Image = img;
    picBox.SizeMode = PictureBoxSizeMode.Zoom;
    picBox.BackColor = Color.Transparent;

    int picCenterX = (rect.Width - picBox.Width) / 2 + rect.Location.X;
    int picCenterY = (rect.Height - picBox.Height) / 2 + rect.Location.Y;

    picBox.Location = new System.Drawing.Point(picCenterX, picCenterY);
}
正如您所看到的,无论图像有多大,它的大小都取决于椭圆的高度和宽度,这与dbvega的方法不同,dbvega的方法中,图像的大小是相同的,必须进行裁剪才能适合椭圆。 此外,使用
PictureBox
还有许多优点,例如为其分配事件、调整其大小、移动其等

用法:

...
int playerWidth = 40;
int playerHeight = 40;
int xPosp = 0;
int yPosp = 0;

SolidBrush pen1 = new SolidBrush(Color.White);
Rectangle rect = new Rectangle(xPosp, yPosp, playerWidth, playerHeight);
e.Graphics.FillEllipse(pen1, rect);

DrawInEllipse(pictureBox1, your_namespace.Properties.Resources.your_image, rect);
...

您需要搜索如何知道椭圆中最大的矩形(优化问题)

假设
your_image
是资源名,看看如何使用上述函数:

...
int playerwidth = 40;
int playerheight = 40;
int xPosp = 0;
int yPosp = 0;

var rect = new Rectangle(xPosp, yPosp, playerwidth, playerheight);
DrawInEllipse(e.Graphics, Resources.your_image, rect);
...
我希望有帮助


您的答案不是使用图像资源填充椭圆的更好方法。此外,图片框将以矩形显示图像。检查我的答案。他希望圆圈是白色的,你的方式无法做到这一点。你将如何解决这个问题?是的,图像将是矩形的,这就是为什么我补充说他应该将BackColor设置为Transparent。再次检查他的问题,他不想用图像填充椭圆,他想在已经填充的椭圆上添加图像。因此,也许我的答案不是更好的方式,但它比你的更准确。请再次检查我的答案。我已编辑了我的答案。在我看来,没有必要像你那样把事情复杂化,而且我也用同样的图片试过你的代码,但没有编辑它,你的代码不会产生好的结果。
...
int playerwidth = 40;
int playerheight = 40;
int xPosp = 0;
int yPosp = 0;

var rect = new Rectangle(xPosp, yPosp, playerwidth, playerheight);
DrawInEllipse(e.Graphics, Resources.your_image, rect);
...