2013-02-24 48 views
3

我試圖使用allegro將位圖加載到一定大小。將位圖圖像加載到一定大小

al_crate_bitmap(x,y) - 創建一個位圖到一定的大小 al_load_bitmap(filename) - 加載我需要的圖像,但加載到它的原始大小。

我需要加載一個位圖到我設置的大小。有任何想法嗎?

感謝, 桑尼

回答

2

的關鍵是al_draw_scaled_bitmap()。這樣,您可以將任何源位圖以任何新大小粘貼到目標位圖上。所以你可能不需要創建一個新的位圖。您始終可以使用該功能以不同大小繪製位圖。 Allegro 5硬件加速,所以這些類型的操作通常是「免費的」。

直接回答這個問題:

ALLEGRO_BITMAP *load_bitmap_at_size(const char *filename, int w, int h) 
{ 
    ALLEGRO_BITMAP *resized_bmp, *loaded_bmp, *prev_target; 

    // 1. create a temporary bitmap of size we want 
    resized_bmp = al_create_bitmap(w, h); 
    if (!resized_bmp) return NULL; 

    // 2. load the bitmap at the original size 
    loaded_bmp = al_load_bitmap(filename); 
    if (!loaded_bmp) 
    { 
    al_destroy_bitmap(resized_bmp); 
    return NULL; 
    } 

    // 3. set the target bitmap to the resized bmp 
    prev_target = al_get_target_bitmap(); 
    al_set_target_bitmap(resized_bmp); 

    // 4. copy the loaded bitmap to the resized bmp 
    al_draw_scaled_bitmap(loaded_bmp, 
    0, 0,        // source origin 
    al_get_bitmap_width(loaded_bmp),  // source width 
    al_get_bitmap_height(loaded_bmp), // source height 
    0, 0,        // target origin 
    w, h,        // target dimensions 
    0         // flags 
); 

    // 5. restore the previous target and clean up 
    al_set_target_bitmap(prev_target); 
    al_destroy_loaded_bmp(loaded_bmp); 

    return resized_bmp;  
} 

我評論的代碼的基本步驟。請記住,Allegro 5有一個隱含目標,通常是顯示器的後臺緩衝區。但是,如上面的代碼所示,如​​果需要對位圖操作執行位圖,則可以將其他位圖作爲目標。

替代方式,移動目標位以外的功能:

void load_bitmap_onto_target(const char *filename) 
{ 
    ALLEGRO_BITMAP *loaded_bmp; 
    const int w = al_get_bitmap_width(al_get_target_bitmap()); 
    const int h = al_get_bitmap_height(al_get_target_bitmap()); 

    // 1. load the bitmap at the original size 
    loaded_bmp = al_load_bitmap(filename); 
    if (!loaded_bmp) return; 

    // 2. copy the loaded bitmap to the resized bmp 
    al_draw_scaled_bitmap(loaded_bmp, 
    0, 0,        // source origin 
    al_get_bitmap_width(loaded_bmp),  // source width 
    al_get_bitmap_height(loaded_bmp), // source height 
    0, 0,        // target origin 
    w, h,        // target dimensions 
    0         // flags 
); 

    // 3. cleanup 
    al_destroy_bitmap(loaded_bmp); 
} 

ALLEGRO_BITMAP *my_bmp = al_create_bitmap(1000,1000); 
al_set_target_bitmap(my_bmp); 
load_bitmap_onto_target("test.png"); 
// perhaps restore the target bitmap to the back buffer, or continue 
// to modify the my_bmp with more drawing operations. 
+0

太感謝你這一點,正是我需要的。雖然我有點困惑的一部分。 prev_target = al_get_target_bitmap();我不明白pre_target在做什麼? – codingNightmares 2013-02-24 18:17:51

+0

Allegro具有通過al_set_target_bitmap()設置的隱式目標位圖。所有未來的繪圖操作都將完成到該位圖。如果這個函數沒有恢復目標位圖,那麼調用代碼可能沒有意識到目標已經被改變,並且可能意外地繼續在位圖上繪製。通常在A5中,在調用函數之前,您會先處理它,但是我將它留在函數中,以便它可以按原樣使用。 – Matthew 2013-02-24 19:03:39

+0

@codingNightmares,我添加了第二個例子。重點是一個函數不應該有典型的副作用,比如改變目標位圖。所以在第二個例子中,函數只是繪製到當前目標。這種做法通常適合A5的API。 – Matthew 2013-02-24 19:10:53