运行效果:
关键代码:
新增头文件:
//item_text.hpp
#ifndef ITEM_TEXT_HPP_INCLUDED
#define ITEM_TEXT_HPP_INCLUDED
#include "item_i.hpp"class TextItem : public IItem
{
public:TextItem(): _startPosition(0, 0), _endPosition(0, 0){_text = wxT("hello d2schol");}void Draw(wxDC& dc) const;void OnDrawStart(wxPoint const& point) override{_startPosition = point;}void OnDrawEnd(wxPoint const& point) override{_endPosition = point;}private:wxPoint _startPosition, _endPosition;wxString _text;
};#endif // ITEM_TEXT_HPP_INCLUDED
新增源文件
//item_text.cpp
#include "item_text.hpp"
#include <cmath>
#include <wx/font.h>void TextItem::Draw(wxDC& dc) const
{if(_text.IsEmpty()) //空串,直接返回{return; //直接返回,动作干脆利落还可以防止后面发生除零错}int w = std::abs(_endPosition.x - _startPosition.x) / _text.Length();int h = std::abs(_endPosition.y - _startPosition.y);if(w == 0 || h == 0){return;}wxFont old_font = dc.GetFont();wxFont font(wxSize(w, h), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);int x = std::min(_startPosition.x, _endPosition.x);int y = std::min(_startPosition.y, _endPosition.y);dc.SetFont(font);dc.DrawText(_text, x, y);dc.SetFont(old_font);
}
新增加宏: