0

The title is bad so i will explain:

Hi, i created 4 images, in which the character (game character, a car) looks at different directions, every time you press the arrow keys (up looks at up, down looks at down, left looks at left, right looks at right), here is the code:

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
  var path,dleft,dright,dtop,dbot:string; 
begin
path:=paramstr(0);
dleft:=extractfilepath(path)+'Images\Pacman_Left.bmp';
dright:=extractfilepath(path)+'Images\Pacman_Right.bmp';
dtop:=extractfilepath(path)+'Images\Pacman_Top.bmp';
dbot:=extractfilepath(path)+'Images\Pacman_Bot.bmp';

  case Key of
     VK_UP:
    begin
      image6.Picture.LoadFromFile(dtop);
      image6.Top := image6.Top - 10;
      end;
     VK_DOWN:
       begin
       image6.Picture.LoadFromFile(dbot);
      image6.Top := image6.Top + 10;
      end;
    VK_LEFT:
       begin
       image6.Picture.LoadFromFile(dleft);
      image6.Left := image6.Left - 10;
      end;
    VK_RIGHT:
       begin
       image6.Picture.LoadFromFile(dright);
      image6.Left := image6.Left + 10;
  end;
  end;
end;

I think the code i am using is terrible, because if i press a key over than a time, it will reload the image and it will keep doing it as long as i keep pressing the same key, such a waste of ram. What can i do about it? thanks

4

3 回答 3

1

一些改进:首先加载所有图像(例如在应用程序启动时):

var
  bmCarLeft, bmCarRight, bmCarUp, bmCarDown: TBitmap;

...

bmCarLeft := TBitmap.Create;
bmCarLeft.LoadFromFile(dleft);
...

然后你可以做

Image6.Picture.Assign(bmCarSomething)

每次你需要改变它。

于 2013-04-20T23:36:41.200 回答
1

确实有很多方法可以做到这一点。
经典方式:
一张包含您的物品(汽车)所有状态的图片,并使用 Canvas.CopyRect() 方法从一张到另一张绘制适当的图像;
另一种方法:
将所有“精灵”加载到 TImageList 并使用 TImageList.Draw() 方法。
等等。
主要思想:使用目标图片的 Canvas 属性并在其上绘制您想要的内容。

于 2013-04-21T00:55:31.517 回答
1

从长远来看,更改管理图像的方式是最好的,但在短期内,最简单的解决方案是跟踪当前加载的图像,以便仅在实际需要时才可以加载新图像,例如:

type
  eWhichImage = (imgUp, imgDown, imgLeft, imgRight);

const
  ImgFiles: array[eWhichImage] of string = (dtop, dbot, dleft, dright);

procedure TMyForm.ImageNeeded(const Img: eWhichImage);
begin
  if image6.Tag <> Ord(Img) then
  begin
    image6.Picture.LoadFromFile(ImgFiles[Img]);
    image6.Tag := Ord(Img);
  end;
end;

.

case Key of
  VK_UP:
  begin
    ImageNeeded(imgUp);
    image6.Top := image6.Top - 10;
  end;
  VK_DOWN:
  begin
    ImageNeeded(imgDown);
    image6.Top := image6.Top + 10;
  end;
  VK_LEFT:
  begin
    ImageNeeded(imgLeft);
    image6.Left := image6.Left - 10;
  end;
  VK_RIGHT:
  begin
    ImageNeeded(imgRight);
    image6.Left := image6.Left + 10;
  end;
end;
于 2013-04-21T03:47:20.087 回答