LoginSignup
0
1

More than 5 years have passed since last update.

C++ Builder > TCanvas > 凡例を描画する

Last updated at Posted at 2017-03-29
動作環境
C++ Builder XE4

TCanvasで凡例を描画してみた。

参考 http://www.ne.jp/asahi/aaa/tach1394/delphi/0300/03.htm

エラー処理はきちんとしていない。

Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------

static const int kNumColor = 4;

// Microsoft color
// @ http://colorhunt.co/blog/google-microsoft-brand-colors/
static const int baseColors[][3] = {
    { 0x00, 0xA1, 0xF1 }, // R, G, B
    { 0x7C, 0xBB, 0x00 }, // R, G, B
    { 0xFF, 0xBB, 0x00 }, // R, G, B
    { 0xF6, 0x53, 0x14 }, // R, G, B
};

TColor __fastcall TForm1::getTColor(int index)
{
    if (index < 0 || index >= kNumColor) {
        return RGB(0, 0, 0);
    }
    int R = baseColors[index][0];
    int G = baseColors[index][1];
    int B = baseColors[index][2];
    return RGB(R, G, B);
}

void __fastcall TForm1::clearTImage(TImage *imgPtr)
{
    imgPtr->Canvas->Brush->Color = clWhite;
    imgPtr->Canvas->FillRect(Rect(0, 0, imgPtr->Width, imgPtr->Height));
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    drawLegends();
}

void __fastcall TForm1::drawLegends(void)
{
    // 1. 消去
    clearTImage(Image1);

    // 2. 凡例の描画
    int step_y = 20; // 結果を見ながら調整した
    for(int idx=0; idx < kNumColor; idx++) {
        char code = 'A' + idx;
        writeTextOnTImage(Image1, /*x=*/30, /*y=*/10 + step_y * idx, String(code)); // 位置30は任意
        drawLegentColor(Image1, /*x=*/14, /*y=*/14 + step_y * idx, getTColor(/*index=*/idx)); // 位置14は任意
    }
}

void __fastcall TForm1::writeTextOnTImage(TImage *imgPtr, int x, int y, String text)
{
    imgPtr->Canvas->Font->Color = clBlack;
    imgPtr->Canvas->Brush->Color = clWhite; // これがないとdrawLegendColor()の後に文字に背景色が付く
    imgPtr->Canvas->Font->Size = 10; // サイズ10は任意

    imgPtr->Canvas->TextOutW(x, y, text.c_str());
}

void __fastcall TForm1::drawLegentColor(TImage *imgPtr, int x, int y, TColor acolor)
{
    imgPtr->Canvas->Brush->Color = acolor;
    imgPtr->Canvas->FillRect(Rect(x, y, x+10, y+10)); // サイズ10は任意
}
//---------------------------------------------------------------------------

qiita.png

こんな感じで使う。

qiita.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1