【问题标题】:ComboBox Simple with Bitmap带位图的简单组合框
【发布时间】:2013-01-11 17:45:37
【问题描述】:

如何将位图放在样式设置为简单的组合框中?例如,谷歌浏览器右边有星号,火狐浏览器右边有箭头。我试过这段代码:

procedure TForm2.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
ComboBox: TComboBox;
bitmap: TBitmap;
begin
ComboBox := (Control as TComboBox);
Bitmap := TBitmap.Create;
try
ImageList1.GetBitmap(0, Bitmap);
with ComboBox.Canvas do
begin
  FillRect(Rect);
  if Bitmap.Handle <> 0 then Draw(Rect.Left + 2, Rect.Top, Bitmap);
  Rect := Bounds(Rect.Left + ComboBox.ItemHeight + 2, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top);
  DrawText(handle, PChar(ComboBox.Items[0]), length(ComboBox.Items[0]), Rect, DT_VCENTER+DT_SINGLELINE);
end;
finally
Bitmap.Free;
  end;
end;

有效,但仅适用于样式:csOwnerDrawFixed 和 csOwnerDrawVariable,位图也仅在项目上可见。

谢谢。

【问题讨论】:

  • 不了解 Chrome,但 Firefox 不使用原生控件。
  • 谢谢您,您知道任何可以执行此操作的组件吗?
  • 所有者抽奖组合有什么问题?
  • Chrome 和 Firefox 不使用标准组合框。它们完全是自定义控件。如果您编写自定义控件,您可以让它看起来像您想要的那样,就像 Google 和 Mozilla 开发人员所做的那样。
  • 是的,您必须使用一种 OwnerDraw 样式来自定义 ComboBox 项的外观。如果这不能满足您的需要,请提供您实际尝试完成的屏幕截图(对于我们这些不使用 Chrome 或 Firefox 的人)。

标签: delphi combobox bitmap


【解决方案1】:

...位图也仅在项目上可见。

要在所有者绘制组合框的编辑器中绘制您的位图,请在所有者绘制状态下检查 odComboBoxEdit

type
  TComboBox = class(StdCtrls.TComboBox)
  private
    FBmp: TBitmap;
    FBmpPos: TPoint;
  protected
    procedure DrawItem(Index: Integer; Rect: TRect;
      State: TOwnerDrawState); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

constructor TComboBox.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FBmp := TBitmap.Create;
  FBmp.Canvas.Brush.Color := clGreen;
  FBmp.Width := 16;
  FBmp.Height := 16;
end;

destructor TComboBox.Destroy;
begin
  FBmp.Free;
  inherited Destroy;
end;

procedure TComboBox.DrawItem(Index: Integer; Rect: TRect;
  State: TOwnerDrawState);
begin
  TControlCanvas(Canvas).UpdateTextFlags;
  if Assigned(OnDrawItem) then
    OnDrawItem(Self, Index, Rect, State)
  else
  begin
    Canvas.FillRect(Rect);
    if Index >= 0 then
      Canvas.TextOut(Rect.Left + 2, Rect.Top, Items[Index]);
    if odComboBoxEdit in State then
    begin
      Dec(Rect.Right, FBmp.Width + Rect.Left);
      FBmpPos.X := Rect.Right + Rect.Left;
      FBmpPos.Y := (Height - FBmp.Height) div 2;
      if ItemIndex > -1 then
        Canvas.TextOut(Rect.Left + 2, Rect.Top, Items[ItemIndex]);
      Canvas.Draw(FBmpPos.X, FBmpPos.Y, FBmp);
    end;
  end;
end;

为了在非所有者绘制的组合框上绘制位图,您必须使用自定义的WM_NCPAINT 处理程序在组合框本身的窗口中进行绘制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2016-06-20
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多