OpenGL接口的基本实现2[转]
目录
绘制矩形
- 注意使用两个矩形相交去判断坐标是否超出范围
void drawFilleRect(int startX,int startY,int w,int h) { int left = tmax<int>(startX,0); int top = tmax<int>(startY,0); int right = tmin<int>(startX + w,_width); int bottom = tmin<int>(startY + h,_height); for (int x = left ; x < right ; ++ x) { for (int y = top ; y < bottom ; ++ y) { setPixelEx(x,y,_color); } } } inline void setPixelEx(unsigned x,unsigned y,Rgba color) { _buffer[y * _width + x] = color; }
矩形渐变颜色(插值)
void drawRect(const int2* points,const Rgba* colors) { int left = tmax<int>(points[0].x,0); int top = tmax<int>(points[0].y,0); int right = tmin<int>(points[2].x,_width); int bottom = tmin<int>(points[2].y,_height); float w = right - left; float h = bottom - top; for (int x = left ; x < right ; ++ x) { Rgba color1 = colorLerp(colors[0],colors[1],(x - left)/w); Rgba color2 = colorLerp(colors[3],colors[2],(x - left)/w); for (int y = top ; y < bottom ; ++ y) { Rgba color = colorLerp(color1,color2,(y - top)/h); setPixelEx(x,y,color); } } } inline void setPixelEx(unsigned x,unsigned y,Rgba color) { _buffer[y * _width + x] = color; } inline Rgba4Byte colorLerp(const Rgba4Byte& c1, const Rgba4Byte& c2, float s) { Rgba4Byte color; color._r = (unsigned char)(c1._r + s * (c2._r - c1._r)); color._g = (unsigned char)(c1._g + s * (c2._g - c1._g)); color._b = (unsigned char)(c1._b + s * (c2._b - c1._b)); color._a = (unsigned char)(c1._a + s * (c2._a - c1._a)); return color; }
- 调用:
CELL::int2 pt[] = { CELL::int2(10,10), CELL::int2(110,10), CELL::int2(110,110), CELL::int2(10,110), }; CELL::Rgba colors[] = { CELL::Rgba(255,0,0), CELL::Rgba(0,255,0), CELL::Rgba(0,0,255), CELL::Rgba(255,255,255), }; raster.drawRect(pt,colors);
Span(int xStart,int xEnd,int y) { if (xStart < xEnd) { _xStart = xStart; _xEnd = xEnd; _y = y; } else { _xStart = _xEnd; _xEnd = _xStart; _y = y; } }