Render a section of an image to a Bitmap C# Winforms

霸气de小男生 提交于 2019-12-24 00:54:47

问题


I'm working on a Map Editor for an XNA game I'm designing in my free time. The pieces of art used in the map are stored on a single texture and rectangles are stored with coordinates and widths etc.

In the winforms application I can add segments by selecting the segment I want from a listbox, which is populated from the array of possible segments.

Problem is I would like to be able to show a preview of the segment selected and, since it is stored on a common texture, I cant simply set a picturebox to display the image.

Is there anyway of using the rectangle information (.x, .y, .width, .height) to display only the section of the image in a picturebox, or to blit the section to a bitmap and display that?

Many Thanks

Michael Allen


回答1:


You probably want to look into the GDI library. Using the Image or Bitmap object and the Graphics.DrawImage() together will get what you're looking for.

private void DrawImageRectRect(PaintEventArgs e)
{

    // Create image.
    Image newImage = Image.FromFile("SampImag.jpg");

    // Create rectangle for displaying image.
    Rectangle destRect = new Rectangle(100, 100, 450, 150);

    // Create rectangle for source image.
    Rectangle srcRect = new Rectangle(50, 50, 150, 150);
    GraphicsUnit units = GraphicsUnit.Pixel;

    // Draw image to screen.
    e.Graphics.DrawImage(newImage, destRect, srcRect, units);
}

You also might be interested in using XNA within your WinForm instead of using PictureBoxes and GDI. It's not 100% supported yet, but a tutorial on that can be found here.




回答2:


You can use Graphics.DrawImage() and that will accept a Rectangle.



来源:https://stackoverflow.com/questions/837423/render-a-section-of-an-image-to-a-bitmap-c-sharp-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!