图像RotateFlip仅在直接调用时有效

时间:2014-02-26 23:51:34

标签: c# image rotation

我的精灵课程是这样的:

public class Sprite : System.ICloneable
{
    public Image SpriteImage { get; private set; }
    public Image SpriteMask { get; private set; }

    public Sprite(Image img, Image maskImg = null)
    {
        this.SetImage(img, maskImg);
    }

    public void SetImage(Image img, Image maskImg = null)
    {
        this.SpriteImage = new Bitmap(img,img.Width,img.Height);

        if (maskImg != null)
        {
            this.SpriteMask = new Bitmap(maskImg, maskImg.Width, maskImg.Height);
        }
        else
        {
            this.SpriteMask = this.SpriteImage;
        }
    }

    public virtual object Clone()
    {
        return new Sprite(this.SpriteImage,this.SpriteMask);
    }

    public void FlipHorizontally()
    {
        this.SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
        this.SpriteMask.RotateFlip(RotateFlipType.RotateNoneFlipX);
    }

    public void FlipVertically()
    {
        this.SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
        this.SpriteMask.RotateFlip(RotateFlipType.RotateNoneFlipY);
    }
}

因为我有SpriteMask和SpriteImage,所以我创建了一个旋转它们的函数,没有麻烦。在另一堂课中我有:

public void ChangeDirection(bool facingRight)
{
    if (facingRight != this.FacingRight)
    {

        for(int i = 0; i < this.Sprites.Count; i++)
        {
            this.Sprites[i].FlipHorizontally();
        }

        foreach (Weapon weapon in this.CollectedWeapons)
        {
            weapon.ChangeDirection(facingRight);
        }
        this.FacingRight = facingRight;
    }
}

this.Sprites是List<Sprite> Sprites;。现在,当这段代码运行时,精灵不会翻转,但如果我将sprite.FlipHorizontally更改为this.Sprites[i].SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);,它就能正常工作。这是为什么?

1 个答案:

答案 0 :(得分:1)

Sprite构造函数中,您允许sprite mask参数为null。如果它为null,请查看您的操作:

if (maskImg != null)
{
    this.SpriteMask = new Bitmap(maskImg, maskImg.Width, maskImg.Height);
}
else
{
    this.SpriteMask = this.SpriteImage;
}

您将SpriteMask设置为SpriteImage - 因为图片是参考类型,您只需指定参考。仍然只有一个Image对象,但两个变量都指向它。当你打电话:

public void FlipHorizontally()
{
    this.SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
    this.SpriteMask.RotateFlip(RotateFlipType.RotateNoneFlipX);
}

...由于SpriteImageSpriteMask是同一个对象,您正在翻转图像,然后再将其翻转回来。如果未提供掩码,您可以考虑为掩码制作精灵图像的副本:

if (maskImg != null)
{
    this.SpriteMask = new Bitmap(maskImg, maskImg.Width, maskImg.Height);
}
else
{
    this.SpriteMask = new Bitmap(this.SpriteImage);
}