如何绘制png图像的一部分c#

时间:2014-06-12 00:38:21

标签: c# drawing sprite-sheet

我正在尝试绘制.png图像的一部分,但我发现的代码无效。这是我的代码

        //define canvas
        canvas = pb.CreateGraphics();
        sPicture = new Bitmap(pb.Width, pb.Height);
        sCanvas = Graphics.FromImage(sPicture);

        // Create a Bitmap object from a file.
        Image image = Image.FromFile(@"");

        // Clone a portion of the Bitmap object.
        Rectangle cloneRect = new Rectangle(0, 0, 11, 6);
        System.Drawing.Imaging.PixelFormat format =
            image.PixelFormat;
        Image cloneBitmap = image.Clone(cloneRect, format); //Error: No overload for method 'Clone' takes2 arguments

        // Draw the cloned portion of the Bitmap object.
        canvas.DrawImage(cloneBitmap, 0, 0);

这是一张精灵表,谢谢。

1 个答案:

答案 0 :(得分:1)

您不需要使用Clone(),您可以使用Graphics.DrawImage()直接执行此操作。看起来你正试图在WinForms中这样做。如果,那么为要绘制的控件处理OnPaint。在下面的示例中,我直接在表单上绘图。

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics graphics = e.Graphics;

    int width = 60;
    int height = 60;

    // Create a Bitmap object from a file.
    Image sourceImage = Image.FromFile(@"C:\Users\Mike\Downloads\logo.png");

    // Draw a portion of the source image.
    Rectangle sourceRect = new Rectangle(0, 0, width, height);
    graphics.DrawImage(sourceImage, 0, 0, sourceRect, GraphicsUnit.Pixel);
}

如果您想在没有WinForms的情况下执行此操作,则需要创建目标Graphics实例的额外步骤。

    int width = 60;
    int height = 60;

    // Create a Bitmap object from a file.
    Image sourceImage = Image.FromFile(@"C:\Users\Mike\Downloads\logo.png");

    // Create a drawing target
    Bitmap bitmap = new Bitmap(width, height, sourceImage.PixelFormat);
    Graphics graphics = Graphics.FromImage(bitmap);       

    // Draw a portion of the source image.
    Rectangle sourceRect = new Rectangle(0, 0, width, height);
    graphics.DrawImage(sourceImage, 0, 0, sourceRect, GraphicsUnit.Pixel);

    // Save
    bitmap.Save(@"C:\Users\Mike\Downloads\out.png");