我正在尝试使用 allegro 将位图加载到特定大小。
al_crate_bitmap(x,y) - 创建一个特定大小的位图 al_load_bitmap(filename) - 加载我需要的图像,但要加载到它的原始大小。
我需要将位图加载到我设置的大小。有任何想法吗?
谢谢,桑尼
关键是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.