2010-04-16 94 views
1

有一些我很想念。假設我有以下代碼:GDI + DrawImage函數

private Bitmap source = new Bitmap (some_stream); 
Bitmap bmp = new Bitmap(100,100); 
Rectangle newRect = new Rectangle(0, 0, bmp.Width, bmp.Height); 
Rectangle toZoom= new Rectangle(0, 0, 10, 10); 

Graphics g = Graphics.FromImage(bmp); 
g.DrawImage(source, newRect, toZoom, GraphicsUnit.Pixel); 

我的目標是放大源圖片左上角的1​​0x10像素。創建圖形對象g並調用DrawImage之後:所請求的矩形(toZoom)將被複制到bmp中,還是會顯示在屏幕上?我有點困惑,有人可以澄清嗎?

回答

1

你的代碼只會給你一個內存位圖(它不會自動顯示到屏幕上)。顯示一個簡單的辦法是把你的窗體上的100×100 PictureBox,和(以上使用Bitmap從您的代碼)設置其屬性Image像這樣:

pictureBox1.Image = bmp; 

而且,你會想一些using塊代碼:

using (private Bitmap source = new Bitmap (some_stream)) 
{ 
    Bitmap bmp = new Bitmap(100,100); 
    Rectangle newRect = new Rectangle(0, 0, bmp.Width, bmp.Height); 
    Rectangle toZoom= new Rectangle(0, 0, 10, 10); 
    using (Graphics g = Graphics.FromImage(bmp)) 
    { 
     g.DrawImage(source, newRect, toZoom, GraphicsUnit.Pixel); 
    } 
    pictureBox1.Image = bmp; 
} 

注意,沒有using塊與bmp - 這是因爲你設置它作爲圖片框的Image屬性。 using塊會在塊的作用域的末尾自動調用對象的Dispose方法,因爲它仍將被使用,所以您不希望這樣做。

0

它將被複制並不顯示。