簡體   English   中英

在TListView中將子項目圖像居中

[英]Center subitem images in a TListView

是否可以在TListView固定subitem圖像的繪制,以使它們不會像圖像中所示的那樣在左側被切除?
在此處輸入圖片說明

好吧, Pieter van Wyk ,我做了一個最小的示例,說明如何所有者繪制TListView組件以將圖像居中於子項中。

答案已被重寫。 為了減小答案的大小,我刪除了未使用和錯誤的部分。 以前的版本可以在問題編輯的歷史記錄中找到。

下圖顯示了新代碼的工作。
橙色行是選定的行。 在此處輸入圖片說明
所選行上的圖像周圍帶有白色。 這不是錯誤-它是具有此類填充的源圖像。

有一些代碼可以執行與圖片相同的操作:

procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect;
  State: TOwnerDrawState);
var
  Bmp: TBitmap;
  Image: TBitmap;
  R: TRect;
  CenterH: Integer;
  CenterV: Integer;
  ImageIndex: Integer;
  ItemWidth: Integer;
  i: Integer;
begin
  // Set initial legth of point at the end of which image will be drawn.  
  // Column 0 is a "fixed" column
  ItemWidth := Sender.Column[0].Width;
  R := Rect;

  Bmp := TBitmap.Create;
  try
    Image := TBitmap.Create;
    try
      Bmp.SetSize(R.Width, R.Height);

      // Make fill for item
      if Item.Selected then
        Bmp.Canvas.Brush.Color := clWebOrange
      else
        Bmp.Canvas.Brush.Color := clMoneyGreen;
      Bmp.Canvas.FillRect(Bmp.Canvas.ClipRect);

      // Output image associated with 'fixed' column
      TListView(Sender).SmallImages.GetBitmap(Item.ImageIndex, Image);
      CenterH := (Sender.Column[0].Width - Image.Width) div 2;
      CenterV := (R.Height - Image.Height) div 2;
      Bmp.Canvas.Draw(CenterH, CenterV, Image);

      // Output text
      Bmp.Canvas.TextOut(CenterH + Image.Width + 6, 6, Item.Caption);

      // Draw sub-items
      for i:=0 to Item.SubItems.Count - 1 do
        begin
          // Obtain index of image
          ImageIndex := Item.SubItemImages[i];

          // Get associated image
          TListView(Sender).SmallImages.GetBitmap(ImageIndex, Image);

          // Center image
          CenterH := (Sender.Column[i+1].Width - Image.Width) div 2;
          CenterV := (R.Height - Image.Height) div 2;

          // Output image
          Bmp.Canvas.Draw(ItemWidth + CenterH, CenterV, Image);

          // Increase point where image started to be drawn
          Inc(ItemWidth, Sender.Column[i+1].Width);
        end;

      // Draw ready item's image onto sender's canvas
      Sender.Canvas.Draw(R.Left, R.Top, Bmp);
    finally
      Image.Free;
    end;
  finally
    Bmp.Free;
  end;
end;

要應用此代碼,必須激活OwnerDraw屬性

請參見導致docs.embarcadero TListView.OwnerDraw屬性 我還想顯示來自上面鏈接的報價:

將OwnerDraw設置為true以允許列表視圖接收OnDrawItem事件,而不是列表項的默認呈現。

PS
調整列的大小后,可能會出現一些graphical artifacts -只需嘗試以隱藏(最小列的可能大小)和顯示圖像(任何超出關聯圖像大小的列的大小)的方式來調整列的大小,您將看到我的意思

PSS
繪制子項目的文本,我留給您作為作業;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM