2013-01-18 66 views
2

所以我是新來的德爾福,我有一個按鈕,當它被點擊它打開一個OpenPictureDialog。然後我想創建一個彈出框,並將該圖片加載到該框中。我不確定最好的方法是什麼?德爾福彈出框與圖像

我正在考慮在按鈕單擊事件上創建一個新窗體,然後將圖像放入該窗體中,但我無法弄清楚如何將TImage傳遞給窗體構造函數。

OpenPictureDialog1.Execute; 
img.Picture.LoadFromFile(OpenPictureDialog1.FileName); 
TForm2.Create(Application, img).Show; 

有沒有人有更好的想法,如何做到這一點或解決我想要做的事情?

謝謝。

回答

6

你最好把TImage組件在您的輔助形式,並通過文件名,例如,創建一個表單這樣一個新的構造:

type 
    TForm2 = class(TForm) 
    Image1: TImage; 
    private 
    public 
    constructor CreateWithImage(AOwner: TComponent; AImgPath: string); 
    end; 

... 
implementation 
... 

constructor TForm2.CreateWithImage(AOwner: TComponent; AImgPath: string); 
begin 
    Create(AOwner); 
    Image1.Picture.LoadFromFile(AImgPath); 
end; 

然後,您可以創建和顯示你的表格是這樣:

procedure TForm1.Button1Click(Sender: TObject); 
var 
    Form2: TForm2; 
begin 
    if OpenPictureDialog1.Execute then 
    begin 
    Form2 := TForm2.CreateWithImage(Self, OpenPictureDialog1.FileName); 
    Form2.Show; 
    end; 
end; 

編輯

如果你想在運行時創建的圖像,你可以做這樣的:

type 
    TForm2 = class(TForm) 
    private 
    FImage: TImage; //this is now in the private section, 
        //and not the default (published) 
    public 
    constructor CreateWithImage(AOwner: TComponent; AImgPath: string); 
    end; 

... 
implementation 
... 

constructor TForm2.CreateWithImage(AOwner: TComponent; AImgPath: string); 
begin 
    Create(AOwner); 
    FImage := TImage.Create(Self); 
    FImage.Parent := Self; 
    FImage.Align := alClient; 
    FImage.Picture.LoadFromFile(AImgPath); 
end; 
+0

謝謝,這是一個優雅的解決方案,但我遇到了問題。 「異常類EAccessViolation與消息'模塊中的地址00403B27訪問衝突」如果我註釋掉ImageLoad線,它運行良好。 – user1970794

+0

在使用它們之前,您必須在delphi中創建對象。 'variable = TForm2.Create(Application,img); variable.Show;' - 如果Image1爲NULL,那麼您不會直接在窗體上拖動IMAGE,而只是鍵入代碼。你不能只在聲明變量的表單中寫一行代碼而不創建它。 –

+0

我對Create的圖像變量進行了調用,但仍然出現相同的錯誤。 – user1970794