RAD Studio
ContentsIndex
PreviousUpNext
Replacing the Picture

You can replace the picture in an image control at any time. If you assign a new graphic to a picture that already has a graphic, the new graphic replaces the existing one. 

To replace the picture in an image control, assign a new graphic to the image control's Picture object. 

Creating the new graphic is the same process you used to create the initial graphic , but you should also provide a way for the user to choose a size other than the default size used for the initial graphic. An easy way to provide that option is to present a dialog box. 

With such a dialog box in your project, add it to the uses clause in the unit for your main form. You can then attach an event handler to the FileNew menu item's OnClick event. Here's an example:

procedure TForm1.New1Click(Sender: TObject);
var
Bitmap: TBitmap;{ temporary variable for the new bitmap }
begin
with NewBMPForm do
begin
ActiveControl := WidthEdit;{ make sure focus is on width field }
WidthEdit.Text := IntToStr(Image.Picture.Graphic.Width);{ use current dimensions... }
HeightEdit.Text := IntToStr(Image.Picture.Graphic.Height);{ ...as default }
if ShowModal <> idCancel then{ continue if user doesn"t cancel dialog box }
begin
Bitmap := TBitmap.Create;{ create fresh bitmap object }
Bitmap.Width := StrToInt(WidthEdit.Text);{ use specified width }
Bitmap.Height := StrToInt(HeightEdit.Text);{ use specified height }
Image.Picture.Graphic := Bitmap;{ replace graphic with new bitmap }
CurrentFile := "";{ indicate unnamed file }
     Bitmap.Free;
end;
end;
end;

 

void __fastcall TForm1::New1Click(TObject *Sender)
{
Graphics::TBitmap *Bitmap;
  // make sure focus is on width field
 NewBMPForm->ActiveControl = NewBMPForm->WidthEdit;
  // initialize to current dimensions as default ...
     NewBMPForm->WidthEdit->Text = IntToStr(Image->Picture->Graphic->Width);
NewBMPForm->HeightEdit->Text = IntToStr(Image->Picture->Graphic->Height);
  if (NewBMPForm->ShowModal() != IDCANCEL){        // if user does not cancel dialog...
Bitmap = new Graphics::TBitmap();             // create a new bitmap object
    // use specified dimensions
     Bitmap->Width = StrToInt(NewBMPForm->WidthEdit->Text);
Bitmap->Height = StrToInt(NewBMPForm->HeightEdit->Text);
Image->Picture->Graphic = Bitmap;            // replace graphic with new bitmap
CurrentFile = EmptyStr;                      //indicate unnamed file
        delete Bitmap;
}
}

Note: Assigning a new bitmap to the picture object's Graphic property causes the picture object to copy the new graphic, but it does not take ownership of it. The picture object maintains its own internal graphic object. Because of this, the previous code frees the bitmap object after making the assignment.

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!