Search code examples
user-interfacefiremonkeydelphi-xe8

How to insert images to TImagelist in FireMonkey programmaticaly?


I try to populate TListView

Current code

MyList.Items.Clear;
 for I := 0 to List.Count-1 do
  begin
  Item:=  MyList.Items.Add;
  Item.Text:= List[i];

  si:=ImageList.Source.Add;
  src:='https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg';
  ms:=LoadWebImage(src);
  si. MultiResBitmap.LoadItemFromStream( ms,100);

  Item.ImageIndex := i;

  end;

Images loaded without errors

 function LoadWebImage(url: string) : TMemoryStream;
        var
          idhttp : TIdHTTP;
        begin
          IdHTTP := TIdHTTP.Create(nil);
          Result := TMemoryStream.Create;
          try
            idhttp.Get (url, Result);
            Result.Position := 0;
          finally
            idhttp.Free;
          end;
        end;

In result i see only text and one image when i added manually for test

ItemAppeariance set as ImageListItem


Solution

  • // OMG!! Who created this component? Uses IdHTTP;

    var
      I: Integer;
      Item: TListViewItem;
      src: string;
      ms: TMemoryStream;
      ItemImageIndex: Integer;
      list:TStringList
    //...
        if Assigned(List) then
         begin
         MyList.Items.Clear;
         for I := 0 to List.Count-1 do
          begin
          // Create list view item
          Item:=  MyList.Items.Add;
          Item.Text:= List[i];
    
          // Load image
          src:='http://www.w3schools.com/html/pic_mountain.jpg';
          ms:= LoadWebImage(src);
    
          // Source
          si:=ImageList.Source.Add;
          si.Name:= 'Source'+inttostr(i);
    
          scale:=1;
          si.MultiResBitmap. LoadItemFromStream(ms,scale);
    
    
          W:=si.MultiResBitmap.Bitmaps[scale].Width;    //Get width from scale
          H:=si.MultiResBitmap.Bitmaps[scale].Height;   //Get height from scale
    
          // Destination
          d:=imageList.Destination.Add;
          Layer := d.Layers.Add;
          Layer.SourceRect.Rect := TRectF.Create(0, 0, W , H);   // Create rect W x H
          Layer.Name := si.name;
    
          Item.ImageIndex := i;
    
          end;
         end;
    

    //Load web image

    function LoadWebImage(Url: string): TMemoryStream;
    var
      IdHTTP: TIdHTTP;
    begin
      try
    
        IdHTTP := TIdHTTP.Create(nil);
        result := TMemoryStream.Create;
        try
          IdHTTP.Get(Url, result);
          result.Position := 0;
        finally
          IdHTTP.Free;
        end;
      except
        result := nil;
      end;
    end;