带有自定义背景的按钮,里面有文本 - C++ Builder

Button with custom background, text inside - C++ Builder

我想创建一个带有自定义背景和内部文本的按钮。 (执行时)

但是文字放在图片旁边,从不放在里面。

你知道怎么做吗?

参考,我可以使用所有TMS组件包

TSpeedButtonGlyph 属性 但 IIRC 它们没有将 CaptionGlyph 组合在一起。幸运的是,您可以使用 Graphics::TBitmap 使用背景图像在 运行 上以编程方式创建字形,并在其顶部渲染文本……我不是 Delphi 编码员,但在构建器中它看起来像这个:

Graphics::TBitmap *bmp=new Graphics::TBitmap;
bmp->LoadFromFile("button_background.bmp");
bmp->Canvas->Font->Color=clWhite;
bmp->Canvas->Brush->Style=bsClear;
AnsiString s="caption1"
int x=(bmp->Width-bmp->Canvas->TextWidth(s))/2;
int y=(bmp->Height-bmp->Canvas->TextHeight(s))/2;
bmp->TextOutA(x,y,s);
bmp->SaveToFile("button1.bmp");
delete bmp;

因此您可以创建一个实用程序来创建您需要的所有字形,然后在您的项目的 IDE 中使用这些字形。我从未尝试在 运行 时间加载字形,但可能有一种方法(直接在目标 App init 中执行此操作)。

[Edit1] 终于有时间测试了

字形 属性 是位图,因此您可以直接从文件加载...无需 new/delete。如果您想拥有更强大的东西,请看一下。我创建了空的新表单应用程序,上面只有几个 TSpeedButtons 并设置了它们的头寸大小,Caption 如下所示:

并且我使用无缝纹理作为背景(因此我可以使用任何按钮大小而不会出现重新缩放问题...):

然后在 运行 时间像这样初始化我的按钮:

//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
void bt_init(TSpeedButton *bt,Graphics::TBitmap *bmp)
    {
    int x,y,xs,ys;
    AnsiString s;
    // clear caption
    s=bt->Caption; bt->Caption="";
    // prepare glyph
    bt->Glyph->PixelFormat=bmp->PixelFormat;
    bt->Glyph->SetSize(bt->Width,bt->Height);
    // render seamless background (repeat texture)
    xs=bmp->Width;
    ys=bmp->Height;
    for (y=0;y<bt->Width;y+=ys)
     for (x=0;x<bt->Width;x+=xs)
      bt->Glyph->Canvas->Draw(x,y,bmp);
    // set transparent color
    bt->Glyph->Canvas->Pixels[0][bt->Glyph->Height-1]=clBlack;
    // render caption
    bt->Glyph->Canvas->Font->Color=clWhite;
    bt->Glyph->Canvas->Font->Style=TFontStyles()<<fsBold;
    bt->Glyph->Canvas->Brush->Style=bsClear;
    x=(bt->Glyph->Width-bt->Glyph->Canvas->TextWidth(s))/2;
    y=(bt->Glyph->Height-bt->Glyph->Canvas->TextHeight(s))/2;
    bt->Glyph->Canvas->TextOutA(x,y,s);
    }
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner):TForm(Owner)
    {
    Graphics::TBitmap *bmp=new Graphics::TBitmap;
    bmp->LoadFromFile("button.bmp");
    bmp->PixelFormat=pf32bit;
    bt_init(SpeedButton1,bmp);
    bt_init(SpeedButton2,bmp);
    bt_init(SpeedButton3,bmp);
    bt_init(SpeedButton4,bmp);
    delete bmp;
    }
//---------------------------------------------------------------------------

您也可以添加边框渲染(另一种纹理...)。您还可以更改标题渲染(更大的字体或彩色边框以增强对比度)。此处预览:

注意最后一个字形的左下角是透明色。因此,如果您不使用它,请将其设置为纹理中未使用的颜色以避免伪影。

也看看这个:

一些文本视觉改进想法。