Show toolbar

2013年7月16日 星期二

Simple drawing using the GD Libary

標題:GD繪圖範例
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include "gd/gd.h"
#include "gd/gdfontg.h"
#include "gd/gdfontt.h"
#include "gd/gdfonts.h"
#include "gd/gdfontmb.h"
#include "gd/gdfontl.h"
#include <math.h>
using namespace std;

#pragma comment(lib, "lib/bgd.lib")

#define DEG 3.14159/180.

class ERR
{
private:
    int kind;
public:
    ERR(int k) : kind(k){};
    char* message()
    {
        switch(kind)
        {
        case 0:
            return "File Error!";
        case 1:
            return "GD Error!";
        case 2:
            return "File Write Error!";
        case 3:
            return "File Close Error!";
        }
    }
};

void drawstar(gdImagePtr image, float origx, float origy, float r, float angle, int color)
{
    int i = 0;
    float ptx[6],pty[6],pttx[6],ptty[6];
    float temp1,temp2,temp3,temp4;

    for(i=0;i<6;i++)
    {
        ptx[i]=origx+r*sin(72.*i*DEG+angle*DEG);
        pty[i]=origy+r*cos(72.*i*DEG+angle*DEG);

        temp1=cos(54.*DEG-72.*DEG*i-angle*DEG);
        temp2=sin(54.*DEG-72.*DEG*i-angle*DEG);
        temp3=sin(18.*DEG);
        temp4=cos(36.*DEG);

        pttx[i]=origx+r*temp3*temp1/temp4;
        ptty[i]=origy+r*temp3*temp2/temp4;
    }
    for(i=0;i<5;i++)
    {
        gdImageLine(image, (int)ptx[i], (int)pty[i], (int)pttx[i], (int)ptty[i], color);
        gdImageLine(image, (int)pttx[i], (int)ptty[i], (int)ptx[i+1], (int)pty[i+1], color);
    }
}

int main(int argc, _TCHAR* argv[])
{
    int i = 0;
    FILE *out;
    int size;
    char *data;

    gdImagePtr im = gdImageCreate(500, 500);
    
    int white =  gdImageColorAllocate(im, 255, 255, 255), //Background
        black =  gdImageColorAllocate(im, 0, 0, 0),
        blue =   gdImageColorAllocate(im, 0, 0, 255),
        cyan =   gdImageColorAllocate(im, 0, 255, 255),
        green =  gdImageColorAllocate(im, 128, 255, 0),
        red =    gdImageColorAllocate(im, 255, 0, 0),
        purple = gdImageColorAllocate(im, 255, 0, 255),
        orange = gdImageColorAllocate(im, 255, 128, 0),
        yellow = gdImageColorAllocate(im, 255, 255, 0);

    out = fopen("image.png", "wb");
    try
    {
        if (out) {
            for(i=0;i<72;i++)
            {
                drawstar(im, 250+5*i*sin(i*10*DEG), 250+5*i*cos(i*10*DEG), 30, 180, black);
            }

            data = (char *) gdImagePngPtr(im, &size);
            if (!data) {
                throw ERR(1);
            }
            if (fwrite(data, 1, size, out) != size) {
                throw ERR(2);
            }
            if (fclose(out) != 0) {
                throw ERR(3);
            }
            gdFree(data);
        }
        else
        {
            throw ERR(0);
        }
    }
    catch(ERR e)
    {
        cout << e.message() << endl;
    }

    return 0;
}

說明:
簡單使用GD Library進行繪圖。

沒有留言:

張貼留言