3
我试图使用allegro将位图加载到一定大小。将位图图像加载到一定大小
al_crate_bitmap(x,y) - 创建一个位图到一定的大小 al_load_bitmap(filename) - 加载我需要的图像,但加载到它的原始大小。
我需要加载一个位图到我设置的大小。有任何想法吗?
感谢, 桑尼
我试图使用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.
太感谢你这一点,正是我需要的。虽然我有点困惑的一部分。 prev_target = al_get_target_bitmap();我不明白pre_target在做什么? – codingNightmares 2013-02-24 18:17:51
Allegro具有通过al_set_target_bitmap()设置的隐式目标位图。所有未来的绘图操作都将完成到该位图。如果这个函数没有恢复目标位图,那么调用代码可能没有意识到目标已经被改变,并且可能意外地继续在位图上绘制。通常在A5中,在调用函数之前,您会先处理它,但是我将它留在函数中,以便它可以按原样使用。 – Matthew 2013-02-24 19:03:39
@codingNightmares,我添加了第二个例子。重点是一个函数不应该有典型的副作用,比如改变目标位图。所以在第二个例子中,函数只是绘制到当前目标。这种做法通常适合A5的API。 – Matthew 2013-02-24 19:10:53