2017-05-05 102 views
1

從C#和Visual Studio到Delphi 10.1柏林對我來說非常困難,但是一些性能至關重要,而且我還沒有和Delphi一起工作很長時間(超過10年) ,所以我被封鎖了。在運行時創建並填充ImageList

我需要在運行時創建一個ImageList並將其存儲在一個單例對象中,但是由於讀取內存時出現異常,我無法做到這一點。

這裏是我的代碼的摘錄:

ImagesRessource = class 
private 
    _owner: TComponent; 
    _imageList: TimageList; 
    _man24: TPngImage; 
    constructor Create; 
    function GetBmpOf(png: TPngImage): TBitmap; 
public 
    procedure Initialize(own: TComponent); 
end; 

implementation 

constructor ImagesRessource.Create; 
begin 
    ; 
end; 

procedure ImagesRessource.Initialize(owner: TComponent); 
var 
    bmp: TBitmap; 
    RS : TResourceStream; 
begin 
    try 
    _man24 := TPngImage.Create; 
    RS := TResourceStream.Create(hInstance, 'man_24', RT_RCDATA); 
    _man24.LoadFromStream(RS); 
    bmp := GetBmpOf(_man24); 
    _imageList := TimageList.Create(owner); 
    _imageList.Width := 24; 
    _imageList.Height := 24; 
    _imageList.AddMasked(Bmp, Bmp.TransparentColor); // exception read memory here 
    except 
    raise; 
    end; 
end; 

function ImagesRessource.GetBmpOf(png: TPngImage): TBitmap; 
var 
    bmp: TBitmap; 
begin 
    bmp := TBitmap.Create; 
    bmp.Width := png.Width; 
    bmp.Height := png.Height; 
    png.Draw(bmp.Canvas, bmp.Canvas.ClipRect); 
end; 

什麼錯在這裏?

+0

爲什麼你需要創建一個ImageList,從ResourceStream中讀取圖像並存儲到imagelist中?也許你應該把ImageList放入一個表單或數據模塊中,並在設計時添加圖像。 – Kohull

+3

使用資源是明智的做法@Kohull。它允許您將資產保存在修訂控制下的單獨文件中。一旦將其放入dfm文件中,維護變得更加困難。 –

回答

1

你不會從GetBmpOf返回任何東西。您必須分配給Result變量)。

function ImagesRessource.GetBmpOf(png: TPngImage): TBitmap; 
begin 
    Result := TBitmap.Create; 
    Result.Width := png.Width; 
    Result.Height := png.Height; 
    png.Draw(Result.Canvas, Result.Canvas.ClipRect); 
end; 

您還漏PNG圖像_man24,這在任何情況下,應該是一個局部變量。你在一些地方硬編碼24的大小,而不是其他地方。你的嘗試,除了塊是毫無意義的。

+0

謝謝你,現在工作如期; –