Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / C++ [игнор отключен] [закрыт для гостей] / Надо пример рисования графика функции в WINAPI / 9 сообщений из 9, страница 1 из 1
19.06.2014, 23:58
    #38674831
stut
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
Кто то может привести код на ВинАПИ чтобы там был нарисован график функции обозначеной координатной сеткой, закрашенными замкнутыми областями. Формула улитка паскаля x=r*cos@, y=r*sin@, r=a*cos@+b? С возможностью масштабирования.
...
Рейтинг: 0 / 0
22.06.2014, 13:47
    #38676551
stut
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
stut, http://www.cplusplus.com/forum/beginner/26214/ http://www.daniweb.com/software-development/cpp/code/216344/draw-a-circle-on-a-windows-form..--вот там есть примеры функции параболы, с библиотеками которых у меня нет, и круга, во втором случае, но это со встроеной функцией элипс. А что изменить в этом коде, чтобы он был применим для рисования улитки?
...
Рейтинг: 0 / 0
23.06.2014, 20:15
    #38677873
stut
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
#include <windows.h>
static HINSTANCE BCX_hInstance;
static int     BCX_ScaleX;
static int     BCX_ScaleY;
static char    BCX_ClassName[2048];
static HWND    Form1;
#define Show(Window) RedrawWindow(Window,0,0,0);ShowWindow(Window,SW_SHOW);
#define Red  RGB(255,0,0)
HWND    BCX_Form(char*,int=0,int=0,int=250,int=150,int=0,int=0);
int     BCX_Circle (HWND,int,int,int,int=0,int=0,HDC=0);
void    FormLoad (void);
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);
// standard main for GUI programs
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE hPrev,LPSTR CmdLine,int CmdShow)
{
 WNDCLASS Wc;
 MSG      Msg;
 // *****************************
 strcpy(BCX_ClassName,"DRAW_CIRCLE");
 // ***************************************
 // Programmer has selected to use pixels
 // (adjust the scaling to 1 accordingly) 
 // ***************************************
 BCX_ScaleX       = 1;
 BCX_ScaleY       = 1;
 BCX_hInstance    =  hInst;
 // ******************************************************
 Wc.style         =  CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
 Wc.lpfnWndProc   =  WndProc;
 Wc.cbClsExtra    =  0;
 Wc.cbWndExtra    =  0;
 Wc.hInstance     =  hInst;
 Wc.hIcon         =  LoadIcon(NULL,IDI_WINLOGO);
 Wc.hCursor       =  LoadCursor(NULL,IDC_ARROW);
 Wc.hbrBackground =  (HBRUSH)(COLOR_BTNFACE+1);
 Wc.lpszMenuName  =  NULL;
 Wc.lpszClassName =  BCX_ClassName;
 RegisterClass(&Wc);
 FormLoad();
  // message loop for events
 while(GetMessage(&Msg,NULL,0,0))
 {
   HWND hActiveWindow = GetActiveWindow();
    if (!IsWindow(hActiveWindow) || !IsDialogMessage(hActiveWindow,&Msg))
    {
      TranslateMessage(&Msg);
      DispatchMessage(&Msg);
    }
  }
 return Msg.wParam;
}
// creates the form (window)
HWND BCX_Form(char *Caption, int X, int Y, int W, int H, int Style, int Exstyle)
{
   HWND  A;
   // assign default style if none is given
   if (!Style)
   {
     Style = WS_MINIMIZEBOX  |
     WS_SIZEBOX      |
     WS_CAPTION      |
     WS_MAXIMIZEBOX  |
     WS_POPUP        |
     WS_SYSMENU;
   }
   A = CreateWindowEx(Exstyle,BCX_ClassName,Caption,
    Style,
    X*BCX_ScaleX,
    Y*BCX_ScaleY,
    (4+W)*BCX_ScaleX,
    (12+H)*BCX_ScaleY,
    NULL,(HMENU)NULL,BCX_hInstance,NULL);
   SendMessage(A,(UINT)WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),
     (LPARAM)MAKELPARAM(FALSE,0));
   return A;
}
// notice conversion from circle(centerX,centerY,radius) to
// ellipse(ulcX,ulcY,lrcX,lrcY)
int BCX_Circle (HWND Wnd,int X,int Y,int R,int Pen,int Fill,HDC DrawHDC)
{
  int a,b=0;
  if (!DrawHDC) 
  {
    DrawHDC=GetDC(Wnd);
    b=1;
  }
  HPEN   hNPen=CreatePen(PS_SOLID,1,Pen);
  HPEN   hOPen=(HPEN)SelectObject(DrawHDC,hNPen);
  HBRUSH hOldBrush;
  HBRUSH hNewBrush;
  if (Fill)
  {
     hNewBrush=CreateSolidBrush(Pen);
     hOldBrush=(HBRUSH)SelectObject(DrawHDC,hNewBrush);
  }
  else
  {
     hNewBrush=(HBRUSH)GetStockObject(NULL_BRUSH);
     hOldBrush=(HBRUSH)SelectObject(DrawHDC,hNewBrush);
  }
  // Win API function
  a = Ellipse(DrawHDC,X-R,Y+R,X+R,Y-R);
  DeleteObject(SelectObject(DrawHDC,hOPen));
  DeleteObject(SelectObject(DrawHDC,hOldBrush));
  if (b) ReleaseDC(Wnd,DrawHDC);
  return a;
}
// form (window) details
// title,upper left corner x,y  width,height
void FormLoad (void)
{
  Form1 = BCX_Form("Draw a circle",50,50,210,210);
  Show(Form1);
}
// standard GUI message handling
LRESULT CALLBACK WndProc (HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
  while(1)
  {
    if (Msg == WM_PAINT)
    {
      //  hwin, centerX, centerY, radius, pencolor 
      BCX_Circle(Form1,100,100,55,Red);
      // you can play around here, add more circles or whatever
      // BCX_Circle(Form1,120,80,55,RGB(0,173,0));  // green
      // BCX_Circle(Form1,80,120,55,RGB(0,0,255));  // blue
      // to draw a circle filled with the pencolor use
      // BCX_Circle(Form1,100,100,55,Red,1);
    }
    break;
  }
  // clean up and exit program
  if (Msg == WM_DESTROY)
  {
     UnregisterClass(BCX_ClassName,BCX_hInstance);
     PostQuitMessage(0);
  }
  return DefWindowProc(hWnd,Msg,wParam,lParam);
}


__Ну вот что здесь изменить?
...
Рейтинг: 0 / 0
23.06.2014, 20:18
    #38677874
stut
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
Или сдесь. Только здесь библиотек у меня нету.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
#include <stdio.h>
#include <windows.h>

#include "resource.h"

// your path for this include may vary
#include "GraphicsFramework.h"


// Global variable to store the graphics framwork object
GraphicsFramework* PGraphics;

HWND HOutput = 0;  // handle to the output control
HWND HDialog = 0;

// function to get the absolute value of an integer
int Abs(int x) {
	if (x < 0)  return -x;
	else        return x;
}

// function to get the sign (+1 or -1) of an integer
int Sign(int x) {
	if (x < 0)  return -1;
	else        return 1;
}
void DrawLine(int x2, int y2, int x1, int y1, unsigned int color)
{
	COLORREF green = RGB(0, 255, 0);     // green color to draw with
	COLORREF purple = RGB(255, 0, 255);  // purple color to draw with
	int dy, dx, y, x;
    // calculate changes in y and x between the points
    dy = y2 - y1;
    dx = x2 - x1;

    // clear the scene and add an axis
    PGraphics->ClearScene(RGB(0, 0, 0));
    PGraphics->AddAxis(RGB(150, 150, 150), 10);

    if (Abs(dy) > Abs(dx)) {
        // since there is a greater change in y than x we must
        // loop in y, calculate x and draw
        for (y=y1; y != y2; y += Sign(dy)) {
            x = x1 + (y - y1) * dx / dy;
            PGraphics->AddPoint(x, y, green);
        }
    }
    else {
        // since there is a greater (or equal) change in x than y we must
        // loop in x, calculate y and draw
        for (x=x1; x != x2; x += Sign(dx)) {
            y = y1 + (x - x1) * dy / dx;
            PGraphics->AddPoint(x, y, green);
        }
    }
	PGraphics->Draw();
	return;

}
void DrawStuff() {
	COLORREF green = RGB(0, 255, 0);     // green color to draw with
	COLORREF purple = RGB(255, 0, 255);  // purple color to draw with

	char str[32];                       // string to store user input
	int h, k;                           // parabola vertex
	double a;                           // parabola constant - might be a decimal
	int x, y;                           // loop and point variables
	int xPrev, yPrev;                   // previous point for drawng line segments
	int ymin, ymax;                     // limits for y loop
	RECT rect;                          // rectangle for the output window

	// get the user input from the edit boxes and 
	// convert string input to integer
	GetDlgItemText(HDialog, IDC_EDIT_VERTEXX, str, 32);
	h = atoi(str);
	GetDlgItemText(HDialog, IDC_EDIT_VERTEXY, str, 32);
	k = atoi(str);
	GetDlgItemText(HDialog, IDC_EDIT_CONSTA, str, 32);
	a = atof(str);                              // use atof to allow user to enter a decimal

	// get the rect for this window
	GetClientRect(HOutput, &rect);

	// use the rectangle info to set up y loop limits
	ymin = -(rect.bottom - rect.top) / 2;
	ymax =  (rect.bottom - rect.top) / 2;

	// clear the scene and add an axis
	PGraphics->ClearScene(RGB(0, 0, 0));
	PGraphics->AddAxis(RGB(150, 150, 150), 10);

	yPrev = ymin;
	xPrev = (int)( a * (yPrev-k) * (yPrev-k) ) + h;
	// loop in y, calculate x and draw
	for (y = ymin; y <= ymax; y++) {
		x = (int)( a * (y-k) * (y-k) ) + h;
		DrawLine(x, y, xPrev, yPrev, green);
		PGraphics->AddPoint(x, y, green); 
	}

	// draw the points
	PGraphics->Draw();
}


/*
DialogProc
this is the window event handler for the main dialog
*/
BOOL CALLBACK DialogProc (HWND hwnd, 
						  UINT message, 
						  WPARAM wParam, 
						  LPARAM lParam)
{
	switch(message)
	{
	case WM_INITDIALOG:
		// dialog is initializing - store the picture box handle in a global variable for later
		HOutput = GetDlgItem(hwnd, IDC_PICTURE_OUTPUT);        

		// instantiate and initialize our graphics framework object
		PGraphics = new GraphicsFramework(HOutput);

		break;

	case WM_COMMAND:
		switch(LOWORD(wParam))
		{
		case IDC_BTN_DRAW:
			// draw button was pressed
			DrawStuff();
			break;
		case IDC_BTN_CLEAR:
			// clear button was pressed so clear the scene and draw the empty scene
			PGraphics->ClearScene(RGB(0, 0, 0));
			PGraphics->Draw();
			break;
		case IDCANCEL:
			// user is quitting so release the GraphicsFramework object and quit
			delete PGraphics;
			PostQuitMessage(0);
			break;
		}

	}
	return FALSE;
}

// this is the main function that starts the application
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, char * cmdParam, int cmdShow)
{
	// create the main window
	// store its handle in a global if needed
	HDialog = CreateDialog (GetModuleHandle(NULL), 
		MAKEINTRESOURCE(IDD_DIALOG1), 
		0, 
		DialogProc);

	// make the dialog visible
	ShowWindow(HDialog, SW_SHOW);

	// standard windows message loop
	MSG  msg;
	int status;
	while ((status = GetMessage (&msg, 0, 0, 0)) != 0)
	{
		if (status == -1)
			return -1;
		// avoid processing messages for the dialog
		if (!IsDialogMessage (HDialog, & msg))
		{
			TranslateMessage ( & msg );
			DispatchMessage ( & msg );
		}
	}

	return (int)(msg.wParam);
}
...
Рейтинг: 0 / 0
23.06.2014, 20:23
    #38677876
MasterZiv
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
stut,

Заменить надо функцию

BCX_Circle(Form1,100,100,55,Red);

на другую, которая будет рисовать график твоей функции.

Кроме этого, твоя улитка -- не совсем функция, это отображение.
Поэтому будут нюансы и с рисованием.
...
Рейтинг: 0 / 0
24.06.2014, 02:23
    #38677983
SashaMercury
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
Stut, зачем вы это делаете если не понимаете как это работает ?
Кривую вы не нарисуете. Нужно писать вспомогательные функции, а не заменить две строчки кода
...
Рейтинг: 0 / 0
24.06.2014, 08:44
    #38678057
stut
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
SashaMercury, в opengl у меня обрисовалось. И там это занимало как раз три строчки кода и цикл for. У меня скорее нету времени на изучение и изменение кода. Ибо график функции надо в несколько вариантах в зависимости от параметров этой улитки. Еще надо нарисовать координатные оси и сетку. Да и масштабировать.
...
Рейтинг: 0 / 0
24.06.2014, 09:45
    #38678107
MasterZiv
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
SashaMercuryStut, зачем вы это делаете если не понимаете как это работает ?
Кривую вы не нарисуете. Нужно писать вспомогательные функции, а не заменить две строчки кода

Ну поточечно можно нарисовать, почему нет?
А можно точки потом соединить линиями, и тоже будет подобие кривой.
Только ему там принцип другой нужен табулирования функции, такой, как в примерах не покатит, потому что у него не функция, а отображение.
...
Рейтинг: 0 / 0
24.06.2014, 10:09
    #38678129
Изопропил
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Надо пример рисования графика функции в WINAPI
MasterZivТолько ему там принцип другой нужен табулирования функции, такой, как в примерах не покатит, потому что у него не функция, а отображение.

не нужно ничего табулировать - просто путь из отрезков нарисовать
...
Рейтинг: 0 / 0
Форумы / C++ [игнор отключен] [закрыт для гостей] / Надо пример рисования графика функции в WINAPI / 9 сообщений из 9, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]