将位图图像加载到特定大小

时间:2013-02-24 02:46:38

标签: image bitmap allegro allegro5

我尝试使用allegro将位图加载到一定大小。

al_crate_bitmap(x,y) - 创建一个特定大小的位图 al_load_bitmap(filename) - 加载我需要的图像,但是加载到原始大小。

我需要将位图加载到我设置的大小。有什么想法吗?

谢谢, 桑尼

1 个答案:

答案 0 :(得分:2)

关键是al_draw_scaled_bitmap()。这样,您可以将任何源位图以任何新大小blit到目标位图上。因此,您实际上可能不需要创建新的位图。您始终可以使用该函数以不同的大小绘制位图。 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.