问题
I am trying to add orange color to my graphics code program. I am using putpixel(int x, int y, int color) function to add color. This function is not allowing to me to do so. Here's my code , Please help me to solve this problem
#include<iostream>
#include<graphics.h>
int main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
int height,width;
height=10;
width=75;
while(height!=43)
{
putpixel(width,height,12); //here i want to add orange color
width++;
if(width==225)
{
width=76;
height++;
}
}
getch();
closegraph();
}
I am trying to build an Indian flag. I am using GNU lib libgraph 1.0.2
回答1:
The code looks like BGI (ancient Borland graphics interface for MS-DOS) which implies either emulation of BGI or real or emulated MS-DOS. Also it usually use only 16 color modes so you got only 16 indexes for colors from standard EGA/VGA palette. In case you use 256 colors you got standard VGA palette.
In this line:
putpixel(width,height,12);
the number 12 is the color used so you need to find which number is the orange you want. You can do that by rendering the whole palette like:
for (x=0;x<16<<2;x++)
for (y=0;y<16;y++)
putpixel(x,y,x>>2);
and count the index from the left starting with zero (do the 256 colors in more lines so you can still count the colors ...) You can also use this
- VGA Color Palettes
Taken image from above link:
the numbers are in hex so 12 = 0x0C
which is red-ish. If your output got similar color than you got the same palette ... If not that means you got different palette (may be Linux or WEB palette)
Here also the standard VGA 256 color palette from the same link:
If wanted color is not present you need to redefine palette which can be done by accessing VGA I/O (reading palette) but will not be possible under Windows or Linux without IO priviledge access. Possibly your gfx lib got some functions doing/emulating it....
Another way is to use dithering so you take red and yellow and mix them (some pixels are red some yellow near by).
PS using put pixel is soo slooow you can render filled rectangles directly with BGI instead. It supports basic geometric shapes and more just see the BGI docs there are tons of them out there. I do not liked BGI at that time and did not use it at all as direct VGA/VESA VRAM access was way faster and better in any way. Using/learning it now is silly (unless you are forced to it by school). There are many alternatives see:
- Graphics rendering in C/C++
If you see the gfxinit()
function in that link there is a routine to change the 256 color VGA palette.
来源:https://stackoverflow.com/questions/48125572/adding-user-defined-color-in-function-putpixelint-x-int-y-int-color