2017-05-05 78 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

谢谢你,现在工作如期; –