覆盖PNG图像保持透明度

时间:2014-04-08 12:07:44

标签: c# png transparency

所以基本上我想做的是将两个.PNG图像重叠为透明背景。一个是用霰弹枪旋转到鼠标位置,另一个是卡通人物,我想放在霰弹枪后面。现在,问题是每当我重叠它们时,PNG图像的透明背景就会受阻,我根本看不到射手。

我已经尝试将射手放在一个面板中,但是将霰弹枪放在其中会使旋转算法失效(使其旋转速度非常慢),我不知道为什么。

任何帮助都会被贬低,谢谢。

我使用的编码: 旋转算法:

private Bitmap rotateImage(Bitmap b, float angle)
{
    //create a new empty bitmap to hold rotated image
    Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
    //make a graphics object from the empty bitmap
    Graphics g = Graphics.FromImage(returnBitmap);
    //move rotation point to center of image
    g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
    //rotate
    g.RotateTransform((int)angle);
    //move image back
    g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
    //draw passed in image onto graphics object
    g.DrawImage(b, new Point(0, 0)); //???
    return returnBitmap;
}

private float CalcAngle(Point TargetPos)
{
    Point ZeroPoint = new Point(pictureBox1.Location.X + pictureBox1.Width / 2, pictureBox1.Location.Y + pictureBox1.Height / 2);
    if (TargetPos == ZeroPoint)
    {
        return 0;
    }

    double angle;
    double deltaX, deltaY;

    deltaY = TargetPos.Y - ZeroPoint.Y;
    deltaX = TargetPos.X - ZeroPoint.X;

    angle = Math.Atan2(deltaY, deltaX) * 180 / Math.PI;
    return (float)angle;
}

private void timer1_Tick(object sender, EventArgs e)
{
    pictureBox1.Image = (Bitmap)backup.Clone();
    //Load an image in from a file
    Image image = new Bitmap(pictureBox1.Image);
    //Set our picture box to that image
    pictureBox1.Image = (Bitmap)backup.Clone();

    //Store our old image so we can delete it
    Image oldImage = pictureBox1.Image;
    //Set angle
    angle = CalcAngle(new Point(Cursor.Position.X, Cursor.Position.Y - 10));
    //Pass in our original image and return a new image rotated X degrees right
    pictureBox1.Image = rotateImage((Bitmap)image, angle);
    if (oldImage != null)
    {
        oldImage.Dispose();
        image.Dispose();
    }
}

2 个答案:

答案 0 :(得分:0)

当您创建新的位图时,尝试使用32 bpp或64 bpp的任何像素格式。请参阅以下代码:

Bitmap returnBitmap = new Bitmap(b.Width, b.Height, PixelFormat.Format64bppPArgb);

答案 1 :(得分:0)

在这里,我将三个不同的png文件相互叠加到一个面板上:

using (Graphics graphic = panel1.CreateGraphics())
{
  using (Image image = Image.FromFile(@"D:\tp3.png")) graphic.DrawImage(image, Point.Empty);
  using (Image image = Image.FromFile(@"D:\tp2.png")) graphic.DrawImage(image, Point.Empty);
  using (Image image = Image.FromFile(@"D:\tp1.png")) graphic.DrawImage(image, Point.Empty);
}

如果您创建一个新的BitMap,请执行@ Palak.Maheria说并使用带有Alpha通道的32位格式!