问问题
606 次
1 回答
4
好吧,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
属性。
请参阅此TListView.OwnerDraw 属性,它导致docs.embarcadero
. 我还想从上面的链接中引用一段话:
将 OwnerDraw 设置为 true 以允许列表视图接收 OnDrawItem 事件,而不是默认呈现列表项。
PS
调整列大小后,可能会有一些graphical artifacts
- 只需尝试以隐藏(列的最小可能大小)和显示图像(任何列大小将超过相关图像大小)的方式调整列大小,您将看到什么我的意思是。
PSS
绘制子项目的文本我留给你作为家庭作业;)
于 2018-08-31T16:21:06.127 回答