XNA如何使xna不能读取透明颜色

问题描述 投票:3回答:4

我对xna很陌生。我刚刚创建了一个带有透明背景(洋红色)的精灵。问题是我的Rectangle正在读取整个Sprite的坐标,而不是可见的。我如何使其仅读取可见的精灵。

myrectangle = new Rectangle(0, 0, box.Width, box.Height);

我想将可见部分放在不透明的位置。提前致谢。

c# xna xna-4.0
4个回答
6
投票

要将颜色转换为透明,请转到纹理属性,内容处理器并启用“颜色键”,然后将键“颜色”设置为洋红色。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9MWGxVMC5wbmcifQ==” alt =“在此处输入图像描述”>

然后将精灵放置在所需的位置,需要设置正确的原点。

要将船中心设置在所需位置,需要设置原点,如下所示:“在此处输入图像描述”“ >>

因此,在绘制时,您需要执行以下操作:

 var origin = new Vector2(40,40);
 spritebatch.Draw(shipTexture, shipPosition, null, Color, origin, ...)

您也可以更改纹理矩形源:

 var texSource = new Rectangle( 25,25, 30,30);
 spritebatch.Draw(shipTexture, shipPosition, texSource, Color)

“在此处输入图像描述”“ >>

尽管如果您想将船定位在其中心,可能需要更改原点

您需要使用诸如Paint之类的程序手动测量所需点的偏移量,然后在Origin方法的参数Draw中设置该偏移量。更好的主意是测量精灵的像素大小(无背景),并在sourceRectangle方法中将其设置为Draw

spritebatch.Draw(textureToDraw, Position, sourceRectangle, Color.White)

[SourceRectangle是可为空的,其默认值是null,在这种情况下,XNA将绘制整个纹理,而您不需要这样做。

使用像洋红色这样的透明颜色编码是非常老式的。如今,我们在图像中使用Alpha来实现这一目标。

我猜想,要做的唯一真实的方法就是搜索颜色数据,以找到最小和最大的x和y坐标,它们的alpha> 0,或者在您的情况下为!= Color.Magenta。

Texture2D sprite = Content.Load<Texture2D>(.....);
int width = sprite.Width;
int height = sprite.Height;
Rectangle sourceRectangle = new Rectangle(int.Max, int.Max, 0, 0);
Color[] data = new Color[width*height];
sprite.GetData<Color>(data);
int maxX = 0;
int maxY = 0;

for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {    
        int index = width * y + x;

        if (data[index] != Color.Magenta)
        {

            if (x < sourceRectangle.X)
                sourceRectangle.X = x;
            else if (x > maxX)
                maxX = x;

            if (y < sourceRectangle.Y)
                sourceRectangle.Y = y;
            else if (y > maxY)
                maxY = y;        
        }
    }
}

sourceRectangle.Width = maxX - sourceRectangle.X;
sourceRectangle.Height = maxY - sourceRectange.Y;

我在VB.Net中使用作弊方法,我认为您可以使用C#进行工作:

    Private Function MakeTexture(ByVal b As Bitmap) As Texture2D
        Using MemoryStream As New MemoryStream
            b.Save(MemoryStream, System.Drawing.Imaging.ImageFormat.Png)
            Return Texture2D.FromStream(XNAGraphics.GraphicsDevice, MemoryStream)
        End Using
    End Function

只要您的位图加载了透明的颜色,此方法就很流畅。


2
投票

您需要使用诸如Paint之类的程序手动测量所需点的偏移量,然后在Origin方法的参数Draw中设置该偏移量。更好的主意是测量精灵的像素大小(无背景),并在sourceRectangle方法中将其设置为Draw


1
投票

使用像洋红色这样的透明颜色编码是非常老式的。如今,我们在图像中使用Alpha来实现这一目标。


0
投票

我在VB.Net中使用作弊方法,我认为您可以使用C#进行工作:

© www.soinside.com 2019 - 2024. All rights reserved.