gpt4 book ai didi

xna - 如何使用 XNA 创建类似 Paint 的应用程序?

转载 作者:行者123 更新时间:2023-12-01 10:02:15 25 4
gpt4 key购买 nike

已涵盖使用 XNA 以编程方式绘制线条的问题 here .但是,我希望允许用户像使用 MS Paint 等绘图应用程序一样在 Canvas 上绘图。

这当然需要鼠标指针位置的每个 x 和/或 y 坐标变化,以导致实时以蜡笔颜色在 Canvas 上绘制线的另一个“点”。

在鼠标移动事件中,为了逐点绘制线,XNA API 考虑因素是什么?当然,从字面上看,我并不是在画一条线,而是一连串的“点”。每个“点”可以而且可能应该比单个像素大。想想用毡尖笔画画。

最佳答案

您提供的文章提出了一种使用图元绘制线条的方法; 矢量图形,换句话说。 Paint 等应用程序大多基于像素(尽管 Photoshop 等更高级的软件具有矢量和光栅化功能)。

位图编辑器

既然你想让它“像画图一样”,我肯定会选择基于像素的方法:

  1. 创建颜色值网格。 (扩展 System.Drawing.Bitmap 类或实现您自己的类。)
  2. 开始(游戏)循环:
    • 处理输入并相应地更新网格中的颜色值。
    • Convert the Bitmap to a Texture2D .
    • 使用 Sprite 批处理或自定义渲染器将纹理绘制到屏幕上。
  3. 如果需要,请保存位图。

在位图上绘制

我在答案的底部添加了我在这里使用的图像类的草稿。但无论如何,代码应该是不言自明的。

如前所述,您还需要实现一种将图像转换为 Texture2D 并将其绘制到屏幕的方法。


首先我们创建一个新的 10x10 图像并将所有像素设置为白色。

var image = new Grid<Color>(10, 10);
image.Initilaize(() => Color.White);

White 10*10 pixel grid

接下来我们设置画笔。画笔本质上只是一个应用于整个图像的功能。在这种情况下,该函数应将指定圆圈内的所有像素设置为深红色。

// Create a circular brush
float brushRadius = 2.5f;
int brushX = 4;
int brushY = 4;
Color brushColor = new Color(0.5f, 0, 0, 1); // dark red

White 10*10 color grid with a circle and cross defining the brush area and center

现在我们应用画笔。请参阅我关于如何 identify the pixels inside a circle 的 SO 回答.您可以将鼠标输入用于画笔偏移,并使用户能够实际在位图上绘制。

double radiusSquared = brushRadius * brushRadius;

image.Modify((x, y, oldColor) =>
{
// Use the circle equation
int deltaX = x - brushX;
int deltaY = y - brushY;
double distanceSquared = Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2);

// Current pixel lies inside the circle
if (distanceSquared <= radiusSquared)
{
return brushColor;
}

return oldColor;
});

White 10*10 color grid with all pixels inside the circle set to a dark red

您还可以在画笔颜色和旧像素之间进行插值。例如,您可以通过让混合量取决于画笔中心和当前像素之间的距离来实现“软”画笔。

White 10*10 color grid with a soft dark red dot

画一条线

为了绘制徒手画线,只需重复应用画笔,每次使用不同的偏移量(取决于鼠标移动):

Drawing a line by repeatedly applying a circular brush


自定义图片类

我显然跳过了一些必要的属性、方法和数据验证,但你明白了:

public class Image
{
public Color[,] Pixels { get; private set; }

public Image(int width, int height)
{
Pixels= new Color[width, height];
}

public void Initialize(Func<Color> createColor)
{
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < Height; y++)
{
Pixels[x, y] = createColor();
}
}
}

public void Modify(Func<int, int, Color, Color> modifyColor)
{
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < Height; y++)
{
Color current = Pixels[x, y];
Pixels[x, y] = modifyColor(x, y, current);
}
}
}
}

关于xna - 如何使用 XNA 创建类似 Paint 的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14589760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com