0

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

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

按钮和旁边的文字

你知道有什么办法吗?

有关信息,我可以使用所有 TMS 组件包

4

1 回答 1

4

TSpeedButtonGlyph有财产,但IIRC他们没有结合Caption在一起Glyph。幸运的是,您可以在运行时使用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] 终于有时间测试了

Glyph 属性是位图,因此您可以直接从文件加载...无需新建/删除。如果您想拥有更强大的功能,请查看此内容。我创建了一个空的新表单应用程序,上面很少TSpeedButtons,并设置了它们的位置大小并Caption如下所示:

IDE设计师

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

质地

并像这样在运行时初始化我的按钮:

//---------------------------------------------------------------------------
#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;
    }
//---------------------------------------------------------------------------

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

预览

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

也看看这个:

对于一些文本视觉改进的想法。

于 2018-07-05T08:19:31.257 回答