fbpx

C++: Greyscale Bars

Bjarne-stroustrup
 

The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.

For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)

For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).

Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.

file greytones.h

#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>

class QPaintEvent ;

class MyWidget : public QWidget {
	public :
	MyWidget( ) ;

	protected :
	void paintEvent( QPaintEvent * ) ;
} ;
#endif
file greytones.cpp

#include <QtGui>
#include "greytones.h"

MyWidget::MyWidget( ) {
	setGeometry( 0, 0 , 640 , 480 ) ;
}

void MyWidget::paintEvent ( QPaintEvent * ) {
	QBrush myBrush( Qt::SolidPattern ) ;
	QPainter myPaint( this ) ;
	int run = 0 ; //how often have we run through the loop ?
	int colorcomp = 0 ;
	for ( int columncount = 8 ; columncount < 128 ; columncount *= 2 ) {
		int colorgap = 255 / columncount ;
		int columnwidth = 640 / columncount ; // 640 being the window width
		int columnheight = 480 / 4 ; //we're looking at quarters
		if ( run % 2 == 0 ) { //we start with black columns 
			colorcomp = 0 ;
		}
		else { //we start with white columns 
			colorcomp = 255 ;
			colorgap *= -1 ; //we keep subtracting color values 
		}
		int ystart = 0 + columnheight * run ; //determines the y coordinate of the first column per row
		int xstart = 0 ;
		for ( int i = 0 ; i < columncount ; i++ ) {
			myBrush.setColor( QColor( colorcomp, colorcomp , colorcomp ) ) ;
			myPaint.fillRect( xstart , ystart , columnwidth , columnheight , myBrush ) ;
			xstart += columnwidth ;
			colorcomp += colorgap ; //we choose the next color 
		}
		run++ ;
	}
}
file main.cpp
#include <QApplication>
#include "greytones.h"

int main( int argc, char * argv[ ] ) {
	QApplication app( argc , argv ) ;
	MyWidget window ;
	window.setWindowTitle( QApplication::translate( "greyScales" , "grey scales demonstration" ) ) ;
	window.show( ) ;
	return app.exec( ) ;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.