// В ChartAppView.cpp
#include <gdiplus.h>
using namespace Gdiplus;
void CChartAppView::OnDraw(CDC* /*pDC*/)
{
CChartAppDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// Инициализируем GDI+ Graphics
CDC* pDCMem = GetDC();
Graphics graphics(pDCMem->m_hDC);
// Настройка параметров рисования
graphics.SetSmoothingMode(SmoothingModeAntiAlias);
// Чтение данных из файла (вызовите один раз, например, в OnInitialUpdate)
CString filePath = _T("data.txt"); // Укажите путь к файлу
if (m_dataRows.empty()) {
if (!ReadDataFromFile(filePath)) {
ReleaseDC(pDCMem);
return;
}
}
// Убедитесь, что данные загружены
if (m_dataRows.size() < 1) {
ReleaseDC(pDCMem);
return;
}
// Определение размеров для диаграмм
CRect clientRect;
GetClientRect(&clientRect);
// Первую диаграмму (Столбчатая с накоплением)
int chartWidth = clientRect.Width() / 2 - 40;
int chartHeight = clientRect.Height() - 100;
int margin = 50;
RectangleF chartArea1(margin, margin, (REAL)chartWidth, (REAL)chartHeight);
// Нарисуем рамку диаграммы
Pen blackPen(Color(255, 0, 0, 0));
graphics.DrawRectangle(&blackPen, chartArea1.X, chartArea1.Y, chartArea1.Width, chartArea1.Height);
// Предполагаем, что m_dataRows[0].values содержит заголовки,
// m_dataRows[1].values и m_dataRows[2].values - два ряда данных
if (m_dataRows.size() < 3) {
ReleaseDC(pDCMem);
return;
}
// Настройка данных
std::vector<std::string> labels;
std::vector<int> values1 = m_dataRows[1].values; // Первые значения
std::vector<int> values2 = m_dataRows[2].values; // Вторые значения
for (const auto& row : m_dataRows) {
labels.push_back(row.label);
}
// Определение максимального значения для масштаба
int maxVal1 = *std::max_element(values1.begin(), values1.end());
int maxVal2 = *std::max_element(values2.begin(), values2.end());
int maxVal = maxVal1 + maxVal2;
// Параметры столбцов
int numBars = labels.size();
float barWidth = (chartArea1.Width - 100) / (float)numBars;
float barSpacing = 20.0f;
// Масштабирование
float scale = chartArea1.Height / (float)(maxVal + 20);
// Рисование столбцов
for (int i = 0; i < numBars; ++i) {
float x = chartArea1.X + 50 + i * (barWidth + barSpacing);
// Первый ряд
float y1 = chartArea1.Y + chartArea1.Height - values1[i] * scale;
graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 255)), x, y1, barWidth, values1[i] * scale);
graphics.DrawRectangle(&blackPen, x, y1, barWidth, values1[i] * scale);
// Второй ряд (накопление)
float y2 = y1 - values2[i] * scale;
graphics.FillRectangle(&SolidBrush(Color(255, 255, 0, 0)), x, y2, barWidth, values2[i] * scale);
graphics.DrawRectangle(&blackPen, x, y2, barWidth, values2[i] * scale);
// Рисование меток
FontFamily fontFamily(L"Arial");
Gdiplus::Font font(&fontFamily, 10, FontStyleRegular, UnitPixel);
SolidBrush textBrush(Color(255, 0, 0, 0));
std::wstring ws(labels[i].begin(), labels[i].end());
PointF pointF(x, chartArea1.Y + chartArea1.Height + 5);
graphics.DrawString(ws.c_str(), -1, &font, pointF, &textBrush);
}
// Вторая диаграмма (Круговая)
// Используем четвертую строку данных
if (m_dataRows.size() < 4) {
ReleaseDC(pDCMem);
return;
}
std::vector<int> pieValues = m_dataRows[3].values;
int pieSum = 0;
for (int val : pieValues) pieSum += val;
// Позиция круговой диаграммы
RectangleF chartArea2(margin + chartWidth + 40, margin, (REAL)chartWidth, (REAL)chartHeight);
// Рисуем круговую диаграмму
float startAngle = 0.0f;
Color colors[] = { Color(255, 255, 0, 0), Color(255, 0, 255, 0),
Color(255, 0, 0, 255), Color(255, 255, 255, 0),
Color(255, 0, 255, 255) };
for (size_t i = 0; i < pieValues.size(); ++i) {
float sweepAngle = (float)pieValues[i] / (float)pieSum * 360.0f;
SolidBrush brush(colors[i % 5]);
graphics.FillPie(&brush, chartArea2.X, chartArea2.Y, chartArea2.Width, chartArea2.Height, startAngle, sweepAngle);
graphics.DrawPie(&blackPen, chartArea2.X, chartArea2.Y, chartArea2.Width, chartArea2.Height, startAngle, sweepAngle);
startAngle += sweepAngle;
}
// Добавление легенды для круговой диаграммы
for (size_t i = 0; i < pieValues.size(); ++i) {
float y = chartArea2.Y + i * 20.0f + 10.0f;
SolidBrush brush(colors[i % 5]);
graphics.FillRectangle(&brush, chartArea2.X + chartArea2.Width + 10, y, 10, 10);
std::wstring ws(labels[i].begin(), labels[i].end());
PointF pointF(chartArea2.X + chartArea2.Width + 25, y);
FontFamily fontFamily(L"Arial");
Gdiplus::Font font(&fontFamily, 10, FontStyleRegular, UnitPixel);
SolidBrush textBrush(Color(255, 0, 0, 0));
graphics.DrawString(ws.c_str(), -1, &font, pointF, &textBrush);
}
ReleaseDC(pDCMem);
}
// ChartAppView.h
#pragma once
#include <vector>
#include <string>
struct DataRow {
std::string label;
std::vector<int> values;
};
class CChartAppView : public CView
{
protected: // создать только из сериализации
CChartAppView() noexcept;
DECLARE_DYNCREATE(CChartAppView)
// Атрибуты
public:
CChartAppDoc* GetDocument() const;
// Операции
public:
// Переопределения
public:
virtual void OnDraw(CDC* pDC); // переопределено для отображения этого вида
virtual void OnInitialUpdate();
// Реализация
public:
virtual ~CChartAppView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
std::vector<DataRow> m_dataRows;
bool ReadDataFromFile(const CString& filePath);
// Созданные функции схемы сообщений
protected:
DECLARE_MESSAGE_MAP()
};
// ChartAppView.cpp
#include "pch.h"
#include "ChartApp.h"
#include "ChartAppDoc.h"
#include "ChartAppView.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <gdiplus.h>
using namespace Gdiplus;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNCREATE(CChartAppView, CView)
BEGIN_MESSAGE_MAP(CChartAppView, CView)
// Стандартные команды печати
//ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
//ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
//ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview)
END_MESSAGE_MAP()
// CChartAppView construction/destruction
CChartAppView::CChartAppView() noexcept
{
// TODO: добавьте код создания
}
CChartAppView::~CChartAppView()
{
}
BOOL CChartAppView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: изменить класс Window или стили посредством изменения
// CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
// CChartAppView drawing
void CChartAppView::OnDraw(CDC* /*pDC*/)
{
CChartAppDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// Инициализируем GDI+ Graphics
CDC* pDCMem = GetDC();
Graphics graphics(pDCMem->m_hDC);
// Настройка параметров рисования
graphics.SetSmoothingMode(SmoothingModeAntiAlias);
graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
// Определение размеров для диаграмм
CRect clientRect;
GetClientRect(&clientRect);
// Первую диаграмму (Столбчатая с накоплением)
int chartWidth = clientRect.Width() / 2 - 40;
int chartHeight = clientRect.Height() - 100;
int margin = 50;
RectangleF chartArea1(margin, margin, (REAL)chartWidth, (REAL)chartHeight);
// Нарисуем рамку диаграммы
Pen blackPen(Color(255, 0, 0, 0));
graphics.DrawRectangle(&blackPen, chartArea1.X, chartArea1.Y, chartArea1.Width, chartArea1.Height);
// Настройка данных
if (m_dataRows.size() < 3) {
ReleaseDC(pDCMem);
return;
}
std::vector<std::string> labels;
std::vector<int> values1 = m_dataRows[1].values; // Первые значения
std::vector<int> values2 = m_dataRows[2].values; // Вторые значения
for (const auto& row : m_dataRows) {
labels.push_back(row.label);
}
// Определение максимального значения для масштаба
int maxVal1 = *std::max_element(values1.begin(), values1.end());
int maxVal2 = *std::max_element(values2.begin(), values2.end());
int maxVal = maxVal1 + maxVal2;
// Параметры столбцов
int numBars = labels.size();
float barWidth = (chartArea1.Width - 100) / (float)numBars;
float barSpacing = 20.0f;
// Масштабирование
float scale = chartArea1.Height / (float)(maxVal + 20);
// Рисование столбцов
for (int i = 0; i < numBars; ++i) {
float x = chartArea1.X + 50 + i * (barWidth + barSpacing);
// Первый ряд
float y1 = chartArea1.Y + chartArea1.Height - values1[i] * scale;
graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 255)), x, y1, barWidth, values1[i] * scale);
graphics.DrawRectangle(&blackPen, x, y1, barWidth, values1[i] * scale);
// Второй ряд (накопление)
float y2 = y1 - values2[i] * scale;
graphics.FillRectangle(&SolidBrush(Color(255, 255, 0, 0)), x, y2, barWidth, values2[i] * scale);
graphics.DrawRectangle(&blackPen, x, y2, barWidth, values2[i] * scale);
// Рисование меток
FontFamily fontFamily(L"Arial");
Font font(&fontFamily, 10, FontStyleRegular, UnitPixel);
SolidBrush textBrush(Color(255, 0, 0, 0));
std::wstring ws(labels[i].begin(), labels[i].end());
PointF pointF(x, chartArea1.Y + chartArea1.Height + 5);
graphics.DrawString(ws.c_str(), -1, &font, pointF, &textBrush);
}
// Вторая диаграмма (Круговая)
// Используем четвертую строку данных
if (m_dataRows.size() < 4) {
ReleaseDC(pDCMem);
return;
}
std::vector<int> pieValues = m_dataRows[3].values;
int pieSum = 0;
for (int val : pieValues) pieSum += val;
// Позиция круговой диаграммы
RectangleF chartArea2(margin + chartWidth + 40, margin, (REAL)chartWidth, (REAL)chartHeight);
// Рисуем круговую диаграмму
float startAngle = 0.0f;
Color colors[] = { Color(255, 255, 0, 0), Color(255, 0, 255, 0),
Color(255, 0, 0, 255), Color(255, 255, 255, 0),
Color(255, 0, 255, 255) };
for (size_t i = 0; i < pieValues.size(); ++i) {
float sweepAngle = (float)pieValues[i] / (float)pieSum * 360.0f;
SolidBrush brush(colors[i % 5]);
graphics.FillPie(&brush, chartArea2.X, chartArea2.Y, chartArea2.Width, chartArea2.Height, startAngle, sweepAngle);
graphics.DrawPie(&blackPen, chartArea2.X, chartArea2.Y, chartArea2.Width, chartArea2.Height, startAngle, sweepAngle);
startAngle += sweepAngle;
}
// Добавление легенды для круговой диаграммы
for (size_t i = 0; i < pieValues.size(); ++i) {
float y = chartArea2.Y + i * 20.0f + 10.0f;
SolidBrush brush(colors[i % 5]);
graphics.FillRectangle(&brush, chartArea2.X + chartArea2.Width + 10, y, 10, 10);
std::wstring ws(labels[i].begin(), labels[i].end());
PointF pointF(chartArea2.X + chartArea2.Width + 25, y);
FontFamily fontFamily(L"Arial");
Font font(&fontFamily, 10, FontStyleRegular, UnitPixel);
SolidBrush textBrush(Color(255, 0, 0, 0));
graphics.DrawString(ws.c_str(), -1, &font, pointF, &textBrush);
}
ReleaseDC(pDCMem);
}
void CChartAppView::OnInitialUpdate()
{
CView::OnInitialUpdate();
CString filePath = _T("data.txt"); // Укажите полный путь при необходимости
ReadDataFromFile(filePath);
}
bool CChartAppView::ReadDataFromFile(const CString& filePath)
{
std::ifstream infile(CT2A(filePath));
if (!infile.is_open()) {
AfxMessageBox(_T("Не удалось открыть файл данных."));
return false;
}
std::string line;
// Чтение заголовков
if (std::getline(infile, line)) {
std::istringstream iss(line);
std::string label;
while (iss >> label) {
DataRow headerRow;
headerRow.label = label;
headerRow.values.clear();
m_dataRows.push_back(headerRow);
}
}
// Чтение значений
while (std::getline(infile, line)) {
std::istringstream iss(line);
int value;
size_t idx = 0;
while (iss >> value && idx < m_dataRows.size()) {
m_dataRows[idx].values.push_back(value);
idx++;
}
}
infile.close();
return true;
}
#ifdef _DEBUG
void CChartAppView::AssertValid() const
{
CView::AssertValid();
}
void CChartAppView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CChartAppDoc* CChartAppView::GetDocument() const // встроенная функция
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CChartAppDoc)));
return (CChartAppDoc*)m_pDocument;
}
#endif //_DEBUG