Colour bars/Display: Difference between revisions

From Rosetta Code
Content added Content deleted
(Rust)
m (size of picture adjusted)
 
(39 intermediate revisions by 15 users not shown)
Line 16: Line 16:
::::::*   white
::::::*   white
<br>
<br>

=={{header|6502 Assembly}}==
Implemented using Easy6502, this displays a pinstripe using the system palette. There are 16 colors, and the bottom 4 bits of A are the color index.
<syntaxhighlight lang="6502asm">lda #0
tax
tay ;clear regs

;video ram on Easy6502 is four pages ranging from $0200-$0500

loop:
sta $0200,x
sta $0220,x
sta $0240,x
sta $0260,x
sta $0280,x
sta $02A0,x
sta $02C0,x
sta $02E0,x

sta $0300,x
sta $0320,x
sta $0340,x
sta $0360,x
sta $0380,x
sta $03A0,x
sta $03C0,x
sta $03E0,x

sta $0400,x
sta $0420,x
sta $0440,x
sta $0460,x
sta $0480,x
sta $04A0,x
sta $04C0,x
sta $04E0,x

sta $0500,x
sta $0520,x
sta $0540,x
sta $0560,x
sta $0580,x
sta $05A0,x
sta $05C0,x
sta $05E0,x

inx
txa ;effectively increment A
cpx #$20 ;32 columns of video memory
beq exit
jmp loop
exit:
brk ;on easy6502 this terminates a program. </syntaxhighlight>



=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE
i,
CH=$02FC, ;Internal hardware value for last key pressed
PALNTSC=$D014, ;To check if PAL or NTSC system is used
PCOLR0=$02C0,PCOLR1=$02C1,
PCOLR2=$02C2,PCOLR3=$02C3,
COLOR0=$02C4,COLOR1=$02C5,
COLOR2=$02C6,COLOR3=$02C7,
COLOR4=$02C8
Graphics(10)
PCOLR0=$04 ;gray
PCOLR1=$00 ;black
IF PALNTSC=15 THEN
PCOLR2=$42 ;red for NTSC
PCOLR3=$C6 ;green for NTSC
COLOR0=$84 ;blue for NTSC
COLOR1=$66 ;magenta for NTSC
COLOR2=$A6 ;cyan for NTSC
COLOR3=$FC ;yellow for NTSC
ELSE
PCOLR2=$22 ;red for PAL
PCOLR3=$B6 ;green for PAL
COLOR0=$74 ;blue for PAL
COLOR1=$48 ;magenta for PAL
COLOR2=$96 ;cyan for PAL
COLOR3=$EC ;yellow for PAL
FI
COLOR4=$0F ;white

FOR i=0 TO 79
DO
Color=i/10+1
Plot(i,0)
DrawTo(i,191)
OD

DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Colour_bars_display.png Screenshot from Atari 8-bit computer]


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<syntaxhighlight lang="actionscript3">
<lang ActionScript3>
package {
package {
Line 48: Line 148:
}
}
</syntaxhighlight>
</lang>


=={{header|Ada}}==
=={{header|Ada}}==
{{libheader|SDLAda}}
{{libheader|SDLAda}}
<lang Ada>with SDL.Video.Windows.Makers;
<syntaxhighlight lang="ada">with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Palettes;
with SDL.Video.Palettes;
Line 100: Line 200:
Window.Finalize;
Window.Finalize;
SDL.Finalise;
SDL.Finalise;
end Colour_Bars_Display;</lang>
end Colour_Bars_Display;</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{libheader|GDI+}} (available at http://www.autohotkey.net/~tic/Gdip.ahk)
{{libheader|GDI+}} (available at http://www.autohotkey.net/~tic/Gdip.ahk)
<lang AutoHotkey>#SingleInstance, Force
<syntaxhighlight lang="autohotkey">#SingleInstance, Force
#NoEnv
#NoEnv
SetBatchLines, -1
SetBatchLines, -1
Line 196: Line 296:
Gdip_Shutdown(pToken)
Gdip_Shutdown(pToken)
ExitApp
ExitApp
Return</lang>
Return</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>
<syntaxhighlight lang="awk">
BEGIN {
BEGIN {
nrcolors = 8
nrcolors = 8
Line 213: Line 313:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==

==={{header|AmigaBASIC}}===
==={{header|AmigaBASIC}}===
<syntaxhighlight lang="amigabasic">SCREEN 1,320,200,5,1

<lang amigabasic>SCREEN 1,320,200,5,1
WINDOW 2,"Color bars",(0,10)-(297,186),15,1
WINDOW 2,"Color bars",(0,10)-(297,186),15,1
FOR a=0 TO 300
FOR a=0 TO 300
LINE (a,0)-(a,186),(a+10)/10
LINE (a,0)-(a,186),(a+10)/10
NEXT
NEXT
loop: GOTO loop</lang>
loop: GOTO loop</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>1 DATA1,12,6,3,14,13,15
<syntaxhighlight lang="applesoftbasic">1 DATA1,12,6,3,14,13,15
2 HOME : GR : FOR I = 1 TO 7
2 HOME : GR : FOR I = 1 TO 7
3 READ C(I) : NEXT
3 READ C(I) : NEXT
4 FOR I = 0 TO 39
4 FOR I = 0 TO 39
5 COLOR= C(I / 5)
5 COLOR= C(I / 5)
6 VLIN 0,39 AT I : NEXT</lang>
6 VLIN 0,39 AT I : NEXT</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> SW_MAXIMIZE = 3
<syntaxhighlight lang="bbcbasic"> SW_MAXIMIZE = 3
SYS "ShowWindow", @hwnd%, SW_MAXIMIZE
SYS "ShowWindow", @hwnd%, SW_MAXIMIZE
VDU 26
VDU 26
Line 255: Line 353:
RECTANGLE FILL C%*W%, 0, W%, H%
RECTANGLE FILL C%*W%, 0, W%, H%
NEXT
NEXT
</syntaxhighlight>
</lang>

==={{header|Chipmunk Basic}}===
The sequence of colors.
<syntaxhighlight lang="basic">
100 rem Colour bars/Display
110 graphics 0 : graphics cls
120 for i = 0 to 7
130 read r,g,b
140 graphics color r,g,b
150 for j = 0 to 79
160 x = i*80+j
170 graphics moveto x,0
180 graphics lineto x,399
190 next j
200 next i
500 data 0,0,0 : rem black
510 data 100,0,0 : rem red
520 data 0,100,0 : rem green
530 data 0,0,100 : rem blue
540 data 100,0,100 : rem magenta
550 data 0,100,100 : rem cyan
560 data 100,100,0 : rem yellow
570 data 100,100,100 : rem white
</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===

This task achieved only on Commodore computers with color capabilities. The example below tested as-is in VICE on the following machines:
This task achieved only on Commodore computers with color capabilities. The example below tested as-is in VICE on the following machines:
* Commodore 64
* Commodore 64
Line 265: Line 386:
* Commodore CBM-II (with VIC-II video)
* Commodore CBM-II (with VIC-II video)
* Commodore SX-64
* Commodore SX-64



It will also work well on the VIC-20 if you either omit line 310 or comment (REM) it out as the VIC-20 has only an eight-color palette.
It will also work well on the VIC-20 if you either omit line 310 or comment (REM) it out as the VIC-20 has only an eight-color palette.
Line 271: Line 391:
This cross-compatibility is achieved by using the PETSCII control codes (CHR$(x)) for changing color, which are generally the same across all platforms, although the system palettes themselves may differ. This is combined with printing a "reverse video" space (solid block) character in the color selected.
This cross-compatibility is achieved by using the PETSCII control codes (CHR$(x)) for changing color, which are generally the same across all platforms, although the system palettes themselves may differ. This is combined with printing a "reverse video" space (solid block) character in the color selected.


<lang gwbasic>5 REM COLOR BARS PROGRAM
<syntaxhighlight lang="gwbasic">5 rem color bars program
10 PRINT CHR$(147);:DIM CO(17):C=1
10 print chr$(147);:dim co(17):c=1
20 READ CO(C):IF CO(C)>0 THEN C=C+1:GOTO 20
20 read co(c):if co(c)>0 then c=c+1:goto 20
25 SP$=" ":H=22:C=C-1:REM SP$=5 SPACES
25 sp$=" ":h=22:c=c-1:rem sp$=5 spaces
30 FOR R=1 TO C STEP INT(C/2)
30 for r=1 to c step int(c/2)
40 FOR H=1 TO 10
40 for h=1 to 10
50 FOR B=R TO (R+INT(C/2))-1
50 for b=r to (r+int(c/2))-1
60 PRINT CHR$(18);CHR$(CO(B));SP$;
60 print chr$(18);chr$(co(b));sp$;
70 NEXT B
70 next b
75 REM CHECK IF PALETTE IS ONLY 8 (VIC-20).
75 rem check if palette is only 8 (vic-20).
76 REM IF SO, WE NEED TO FILL THE LAST TWO SPACES.
76 rem if so, we need to fill the last two spaces.
80 IF C<=8 THEN PRINT " ";
80 if c<=8 then print " ";
90 NEXT H:NEXT R
90 next h:next r
100 GET K$:IF K$="" THEN 100
100 get k$:if k$="" then 100
110 END
110 end
280 REM BECAUSE THE CONTROL CODES FOR COLOR ARE NON-SEQUENTIAL,
280 rem because the control codes for color are non-sequential,
285 REM WE PUT THEM INTO A SEQUENTIAL ARRAY FOR USE
285 rem we put them into a sequential array for use
300 DATA 144,5,28,159,156,30,31,158
300 data 144,5,28,159,156,30,31,158
305 REM OMIT OR REM THE NEXT LINE FOR VIC-20
305 rem omit or rem the next line for vic-20
310 DATA 129,149,150,151,152,153,154,155
310 data 129,149,150,151,152,153,154,155
320 DATA 0:REM DATA TERMINATOR</lang>
320 data 0:rem data terminato</syntaxhighlight>

==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64

' Draw the color bars on an 80 x 25 console using the system palette of 16 colors
' i.e. 5 columns per color
Width 80, 25
Shell "cls"
Locate ,, 0 '' turn cursor off
For clr As UInteger = 0 To 15
Color 0, clr
For row As Integer = 1 to 25
Locate row, clr * 5 + 1
Print Space(5);
Next row
Next clr

Sleep
' restore default settings
Locate ,, 1 '' turn cursor on
Color 7, 0 '' white text on black background</syntaxhighlight>

==={{header|FutureBasic}}===
[[File:ColorBarsDisplayFB300.png|right]]
<syntaxhighlight lang="futurebasic">
void local fn DoIt
long index, x = 0
CFArrayRef colors = @[fn ColorBlack,fn ColorRed,
fn ColorGreen,fn ColorBlue,fn ColorMagenta,
fn ColorCyan,fn ColorYellow,fn ColorWhite]
window 1, @"Color bars/Display", (0,0,480,270), NSWindowStyleMaskTitled
pen -1
for index = 0 to len(colors) - 1
rect fill (x,0,60,270), colors[index]
x += 60
next
end fn

fn DoIt

HandleEvents
</syntaxhighlight>

==={{header|Gambas}}===
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim iColour As Integer[] = [Color.Black, Color.red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.white]
Dim hPanel As Panel
Dim siCount As Short

With Me
.Arrangement = Arrange.Horizontal
.Height = 300
.Width = 400
End With

For siCount = 0 To 6
hpanel = New Panel(Me)
hpanel.Expand = True
hpanel.H = 500
HPanel.Background = iColour[siCount]
Next

End</syntaxhighlight>

==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 GRAPHICS LORES 16
110 SET PALETTE BLACK,RED,GREEN,BLUE,MAGENTA,CYAN,YELLOW,WHITE
120 FOR I=1 TO 7
130 CALL BAR(I)
140 NEXT
150 DEF BAR(C)
160 SET INK C
170 PLOT C*160,0;C*160,719;C*160+152,719;C*160+152,0;C*160,0
180 PLOT C*160+16,16,PAINT
190 END DEF</syntaxhighlight>


==={{header|Liberty BASIC}}===
==={{header|Liberty BASIC}}===
<lang lb>nomainwin
<syntaxhighlight lang="lb">nomainwin
colors$="black red green blue pink cyan yellow white"
colors$="black red green blue pink cyan yellow white"
WindowWidth=DisplayWidth:WindowHeight=DisplayHeight
WindowWidth=DisplayWidth:WindowHeight=DisplayHeight
Line 314: Line 511:
wait
wait
[quit] close #main:end
[quit] close #main:end
</lang>
</syntaxhighlight>


==={{header|Locomotive Basic}}===
==={{header|Locomotive Basic}}===

[[File:CPC color bars.png|thumb|right]]
[[File:CPC color bars.png|thumb|right]]

Show the default MODE 0 palette (includes two blinking colors at the end):
Show the default MODE 0 palette (includes two blinking colors at the end):
<syntaxhighlight lang="locobasic">10 MODE 0:BORDER 23

<lang locobasic>10 MODE 0:BORDER 23
20 FOR x=0 TO 15
20 FOR x=0 TO 15
30 ORIGIN x*40,0
30 ORIGIN x*40,0
40 FOR z=0 TO 39 STEP 4:MOVE z,0:DRAW z,400,x:NEXT z
40 FOR z=0 TO 39 STEP 4:MOVE z,0:DRAW z,400,x:NEXT z
50 NEXT x
50 NEXT x
60 CALL &bb06 ' wait for key press</lang>
60 CALL &bb06 ' wait for key press</syntaxhighlight>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
Press Enter or Escape to exit the program.
Press Enter or Escape to exit the program.
<lang PureBasic>Dim color(7)
<syntaxhighlight lang="purebasic">Dim color(7)
color(0) = RGB($00, $00, $00) ;black
color(0) = RGB($00, $00, $00) ;black
color(1) = RGB($FF, $00, $00) ;red
color(1) = RGB($FF, $00, $00) ;red
Line 361: Line 555:
Until KeyboardPushed(#PB_Key_Escape) Or KeyboardPushed(#PB_Key_Return)
Until KeyboardPushed(#PB_Key_Escape) Or KeyboardPushed(#PB_Key_Return)
CloseScreen()
CloseScreen()
EndIf</lang>
EndIf</syntaxhighlight>
====Alternate method using console====
====Alternate method using console====
<lang PureBasic>DataSection
<syntaxhighlight lang="purebasic">DataSection
;Black, Red, Green, Blue, Magenta, Cyan, Yellow, White
;Black, Red, Green, Blue, Magenta, Cyan, Yellow, White
Data.i 0, 12, 10, 9, 13, 11, 14, 15
Data.i 0, 12, 10, 9, 13, 11, 14, 15
Line 386: Line 580:
ConsoleTitle("Press ENTER to exit"): Input()
ConsoleTitle("Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
<lang runbasic>colors$ = "black,red,green,blue,magenta,cyan,yellow,white"
<syntaxhighlight lang="runbasic">colors$ = "black,red,green,blue,magenta,cyan,yellow,white"
html "<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=4><tr height=70>"
html "<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=4><tr height=70>"
for i = 1 to 8
for i = 1 to 8
html "<td width=20 bgcolor='";word$(colors$,i,",");"'</td>"
html "<td width=20 bgcolor='";word$(colors$,i,",");"'</td>"
next i
next i
html "</tr></table>"</lang>
html "</tr></table>"</syntaxhighlight>
<pre>Output</pre>
<pre>Output</pre>


[[File:ColorBarRunBasic.png]]
[[File:ColorBarRunBasic.png]]

==={{header|SmileBASIC}}===
<syntaxhighlight lang="smilebasic">FOR I=0 TO 7
READ R,G,B
GFILL I*50,0,I*50+49,239,RGB(R,G,B)
NEXT
REPEAT UNTIL BUTTON(0) AND #B

DATA 0,0,0
DATA 255,0,0
DATA 0,255,0
DATA 0,0,255
DATA 255,0,255
DATA 0,255,255
DATA 255,255,0
DATA 255,255,255</syntaxhighlight>


==={{header|TI Basic}}===
==={{header|TI Basic}}===
<LANG>100 REM SMPTE Format Color Bars
<syntaxhighlight lang="basic">100 REM SMPTE Format Color Bars
110 REM with 400 Hz reference tone
110 REM with 400 Hz reference tone
120 CALL CLEAR
120 CALL CLEAR
Line 443: Line 653:
540 NEXT I
540 NEXT I
590 RETURN
590 RETURN
</syntaxhighlight>
</LANG>


==={{header|ZX Spectrum Basic}}===
==={{header|ZX Spectrum Basic}}===
<lang zxbasic>10 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces
<syntaxhighlight lang="zxbasic">10 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces
20 FOR r=0 TO 20: REM There are 21 rows
20 FOR r=0 TO 20: REM There are 21 rows
30 FOR c=0 TO 7: REM We use the native colour sequence here
30 FOR c=0 TO 7: REM We use the native colour sequence here
Line 453: Line 663:
60 NEXT c
60 NEXT c
70 REM at this point the cursor has wrapped, so we don't need a newline
70 REM at this point the cursor has wrapped, so we don't need a newline
80 NEXT r</lang>
80 NEXT r</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
Assuming a terminal with support for ANSI escape sequences, this fills the screen with the colour sequence: black, red, green, blue, magenta, cyan, yellow and white. It then waits for the user to press ''Enter'' before terminating.
Assuming a terminal with support for ANSI escape sequences, this fills the screen with the colour sequence: black, red, green, blue, magenta, cyan, yellow and white. It then waits for the user to press ''Enter'' before terminating.
<lang befunge><v%"P": <<*"(2"
<syntaxhighlight lang="befunge"><v%"P": <<*"(2"
v_:"P"/"["39*,, :55+/68v
v_:"P"/"["39*,, :55+/68v
v,,,";1H" ,+*86%+55 ,+*<
v,,,";1H" ,+*86%+55 ,+*<
73654210v,,\,,,*93"[4m"<
73654210v,,\,,,*93"[4m"<
>$:55+%#v_:1-"P"%55+/3g^
>$:55+%#v_:1-"P"%55+/3g^
39*,,,~@>48*,1-:#v_$"m["</lang>
39*,,,~@>48*,1-:#v_$"m["</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Line 469: Line 679:
===Text Mode===
===Text Mode===
The required functions and structures are in conio.h
The required functions and structures are in conio.h
<syntaxhighlight lang="c">
<lang C>
#include<conio.h>
#include<conio.h>


Line 502: Line 712:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


===Graphics Mode===
===Graphics Mode===
The required functions and structures are in graphics.h, conio.h is included for getch().
The required functions and structures are in graphics.h, conio.h is included for getch().
<syntaxhighlight lang="c">
<lang C>
#include<graphics.h>
#include<graphics.h>
#include<conio.h>
#include<conio.h>
Line 529: Line 739:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
Line 536: Line 746:
file <code>colorbars.h</code>:
file <code>colorbars.h</code>:


<lang cpp>#ifndef MYWIDGET_H
<syntaxhighlight lang="cpp">#ifndef MYWIDGET_H
#define MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QWidget>
Line 553: Line 763:
const int colornumber ;
const int colornumber ;
} ;
} ;
#endif</lang>
#endif</syntaxhighlight>


file <code>colorbars.cpp</code>:
file <code>colorbars.cpp</code>:


<lang cpp>#include <QtGui>
<syntaxhighlight lang="cpp">#include <QtGui>
#include "colorbars.h"
#include "colorbars.h"


Line 583: Line 793:
xstart += rectwidth + 1 ;
xstart += rectwidth + 1 ;
}
}
}</lang>
}</syntaxhighlight>


file <code>main.cpp</code>:
file <code>main.cpp</code>:


<lang cpp>#include <QApplication>
<syntaxhighlight lang="cpp">#include <QApplication>
#include "colorbars.h"
#include "colorbars.h"


Line 596: Line 806:
window.show( ) ;
window.show( ) ;
return app.exec( ) ;
return app.exec( ) ;
}</lang>
}</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
{{works with|OpenCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. terminal-colour-bars.
PROGRAM-ID. terminal-colour-bars.


Line 651: Line 861:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
==={{header|ncurses}}===
==={{header|ncurses}}===
To interface the ncurses C library from Lisp, the ''croatoan'' library is used.
To interface the ncurses C library from Lisp, the ''croatoan'' library is used.
<lang lisp>(defun color-bars ()
<syntaxhighlight lang="lisp">(defun color-bars ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(dotimes (i (height scr))
(dotimes (i (height scr))
Line 664: Line 874:
(refresh scr)
(refresh scr)
;; wait for keypress
;; wait for keypress
(get-char scr)))</lang>
(get-char scr)))</syntaxhighlight>
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
{{libheader| Winapi.Windows}}
Line 671: Line 881:
{{libheader| Vcl.Graphics}}
{{libheader| Vcl.Graphics}}
{{libheader| Vcl.Forms}}
{{libheader| Vcl.Forms}}
<syntaxhighlight lang="delphi">
<lang Delphi>
unit Colour_barsDisplay;
unit Colour_barsDisplay;


Line 720: Line 930:
Invalidate;
Invalidate;
end;
end;
end.</lang>
end.</syntaxhighlight>
Form resource:
Form resource:
<syntaxhighlight lang="delphi">
<lang Delphi>
object fmColourBar: TfmColourBar
object fmColourBar: TfmColourBar
Caption = 'fmColourBar'
Caption = 'fmColourBar'
Line 729: Line 939:
OnResize = FormResize
OnResize = FormResize
end
end
</syntaxhighlight>
</lang>


=={{header|EasyLang}}==
=={{header|EasyLang}}==


[https://easylang.dev/show/#cod=TYyxCoAwDET3fsWNKqjpmMEvKZ1KhUK1UER/34uTQ7i7l0tSqyFiQ4CIQDmiHFF6pacyKzW6hz3PxoqaTyS7dHvrKMZxtR8GzHBnsXz5aHfGgwlDwQw/Qoz2nC5SvnWLewE= Run it]
[https://easylang.online/ide/?run=col%5B%5D%3D%5B%20000%20900%20090%20909%20099%20990%20999%20%5D%0Aw%3D100.0/len%20col%5B%5D%0Afor%20i%20range%20len%20col%5B%5D%0Acolor%20col%5Bi%5D%0Amove%20w%2Ai%200%0Arect%20w%20100%0A. Run it]


<syntaxhighlight lang="text">
<lang easyprog.online>col[] = [ 000 900 090 909 099 990 999 ]
col[] = [ 000 900 090 009 909 099 990 999 ]
w = 100.0 / len col[]
for i range len col[]
w = 100 / len col[]
color col[i]
for i = 1 to len col[]
move w * i 0
color col[i]
rect w 100
move w * (i - 1) 0
rect w 100
.</lang>
.
</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: accessors colors.constants kernel math sequences ui
<syntaxhighlight lang="factor">USING: accessors colors.constants kernel math sequences ui
ui.gadgets ui.gadgets.tracks ui.pens.solid ;
ui.gadgets ui.gadgets.tracks ui.pens.solid ;
IN: rosetta-code.colour-bars-display
IN: rosetta-code.colour-bars-display
Line 766: Line 978:
"bars" open-window
"bars" open-window
] with-ui ;
] with-ui ;
MAIN: colors</lang>
MAIN: colors</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
Line 772: Line 984:
<br> The color bars are shown in Society of Motion Picture and Television Engineers (SMPTE) order.
<br> The color bars are shown in Society of Motion Picture and Television Engineers (SMPTE) order.


<syntaxhighlight lang="forth">
<lang CAMEL99 Forth>
\ Color Bars for TI-99 CAMEL99 Forth
\ Color Bars for TI-99 CAMEL99 Forth


Line 837: Line 1,049:


CR .( Done. Type BARS to run)
CR .( Done. Type BARS to run)
</syntaxhighlight>
</LANG>

=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64

' Draw the color bars on an 80 x 25 console using the system palette of 16 colors
' i.e. 5 columns per color
Width 80, 25
Shell "cls"
Locate ,, 0 '' turn cursor off
For clr As UInteger = 0 To 15
Color 0, clr
For row As Integer = 1 to 25
Locate row, clr * 5 + 1
Print Space(5);
Next row
Next clr

Sleep
' restore default settings
Locate ,, 1 '' turn cursor on
Color 7, 0 '' white text on black background</lang>

=={{header|Gambas}}==
<lang gambas>Public Sub Form_Open()
Dim iColour As Integer[] = [Color.Black, Color.red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.white]
Dim hPanel As Panel
Dim siCount As Short

With Me
.Arrangement = Arrange.Horizontal
.Height = 300
.Width = 400
End With

For siCount = 0 To 6
hpanel = New Panel(Me)
hpanel.Expand = True
hpanel.H = 500
HPanel.Background = iColour[siCount]
Next

End</lang>


=={{header|Go}}==
=={{header|Go}}==
{{libheader|Go Graphics}}
{{libheader|Go Graphics}}
<lang go>package main
<syntaxhighlight lang="go">package main


import "github.com/fogleman/gg"
import "github.com/fogleman/gg"
Line 912: Line 1,082:
drawBars(dc)
drawBars(dc)
dc.SavePNG("color_bars.png")
dc.SavePNG("color_bars.png")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 923: Line 1,093:
Terminal-based version.
Terminal-based version.


<lang haskell>#!/usr/bin/env stack
<syntaxhighlight lang="haskell">#!/usr/bin/env stack
-- stack --resolver lts-7.0 --install-ghc runghc --package vty -- -threaded
-- stack --resolver lts-7.0 --install-ghc runghc --package vty -- -threaded


Line 943: Line 1,113:
where attrs = map color2attr colors
where attrs = map color2attr colors
nBars = length colors
nBars = length colors
colors = [black, brightRed, brightGreen, brightMagenta, brightCyan, brightYellow, brightWhite]
colors = [black, brightRed, brightGreen, brightBlue, brightMagenta, brightCyan, brightYellow, brightWhite]
color2attr c = Attr Default Default (SetTo c)
color2attr c = Attr Default Default (SetTo c)


main :: IO ()
main = do
main = do
cfg <- standardIOConfig
cfg <- standardIOConfig
Line 960: Line 1,131:
_ -> return ()
_ -> return ()
showBars bounds
showBars bounds
shutdown vty</lang>
shutdown vty</syntaxhighlight>

[[File:Haskell_Colourbars_A_0.png|700px]]


Graphical version using SFML.
Graphical version using SFML.


<lang haskell>-- Before you can install the SFML Haskell library, you need to install
<syntaxhighlight lang="haskell">-- Before you can install the SFML Haskell library, you need to install
-- the CSFML C library. (For example, "brew install csfml" on OS X.)
-- the CSFML C library. (For example, "brew install csfml" on OS X.)


Line 1,014: Line 1,187:
withResource (createRenderWindow vMode "color bars" wStyle Nothing) $
withResource (createRenderWindow vMode "color bars" wStyle Nothing) $
\wnd -> withResources (mapM (makeBar $ barSize vMode) $ zip colors [0..]) $
\wnd -> withResources (mapM (makeBar $ barSize vMode) $ zip colors [0..]) $
\bars -> loop wnd bars</lang>
\bars -> loop wnd bars</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
The procedure below is generalized to take a description of a ''test card'' and display it.
The procedure below is generalized to take a description of a ''test card'' and display it.
[[File:Colourbars_Simple_Unicon.png|thumb|right]]
[[File:Colourbars_Simple_Unicon.png|thumb|right]]
<lang Icon>link graphics,printf
<syntaxhighlight lang="icon">link graphics,printf
procedure main() # generalized colour bars
procedure main() # generalized colour bars
Line 1,055: Line 1,228:
bar(width) ] ),
bar(width) ] ),
band(height) ])
band(height) ])
end</lang>
end</syntaxhighlight>


The following example is a wee tiny bit more interesting.
The following example is a wee tiny bit more interesting.
[[File:Colourbars_SMPTE_Unicon.png|thumb|right]]
[[File:Colourbars_SMPTE_Unicon.png|thumb|right]]
<lang Icon>procedure SMPTE_TestCard() #: return structure with 480i(ish) testcard
<syntaxhighlight lang="icon">procedure SMPTE_TestCard() #: return structure with 480i(ish) testcard
return testcard(,"SMPTE TV Test Card",width := 672,height := 504,
return testcard(,"SMPTE TV Test Card",width := 672,height := 504,
[ band( 1, [ bar( 1, "#c0c0c0"),
[ band( 1, [ bar( 1, "#c0c0c0"),
Line 1,087: Line 1,260:
bar(width) ] ),
bar(width) ] ),
band(height) ])
band(height) ])
end</lang>
end</syntaxhighlight>


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
Line 1,095: Line 1,268:
=={{header|J}}==
=={{header|J}}==


<lang j> load 'viewmat'
<syntaxhighlight lang="j"> load 'viewmat'
size=: 2{.".wd'qm' NB. J6
size=: 2{.".wd'qm' NB. J6
size=: getscreenwh_jgtk_ '' NB. J7
size=: getscreenwh_jgtk_ '' NB. J7
'rgb'viewmat (|.size){. (>.&.(%&160)|.size)$ 20# 256#.255*#:i.8</lang>
'rgb'viewmat (|.size){. (>.&.(%&160)|.size)$ 20# 256#.255*#:i.8</syntaxhighlight>


Note: You need to pick an implementation of <code>size</code> based on the version of J you are using.
Note: You need to pick an implementation of <code>size</code> based on the version of J you are using.


=={{header|Java}}==
=={{header|Java}}==
<lang java>
<syntaxhighlight lang="java">
import java.awt.Color;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics;
Line 1,132: Line 1,305:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>using Images
<syntaxhighlight lang="julia">using Images


colors = [colorant"black", colorant"red", colorant"green", colorant"darkblue",
colors = [colorant"black", colorant"red", colorant"green", colorant"darkblue",
Line 1,147: Line 1,320:
img[:, j:j+wcol] = col
img[:, j:j+wcol] = col
end
end
save("data/colourbars.jpg", img)</lang>
save("data/colourbars.jpg", img)</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>import java.awt.Color
<syntaxhighlight lang="scala">import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics
import javax.swing.JFrame
import javax.swing.JFrame
Line 1,175: Line 1,348:
fun main(args: Array<String>) {
fun main(args: Array<String>) {
ColorFrame(400, 400)
ColorFrame(400, 400)
}</lang>
}</syntaxhighlight>
Editing Babbage problem
Editing Babbage problem

=={{header|Lua}}==
{{libheader|nw}}
{{libheader|cairo}}
<syntaxhighlight lang="lua">local nw = require("nw")
local app = nw:app()
local cw, ch = 320, 240
local win = app:window(cw, ch, "Color Bars", false)
local colors = {{0,0,0}, {1,0,0}, {0,1,0}, {0,0,1}, {1,0,1}, {0,1,1}, {1,1,0}, {1,1,1}}
local unpack = unpack or table.unpack -- polyfill 5.2 vs 5.3
function win:repaint()
local cr = win:bitmap():cairo()
for i = 1, #colors do
cr:rectangle((i-1)*cw/#colors, 0, cw/#colors, ch)
cr:rgb(unpack(colors[i]))
cr:fill()
end
end
win:show()
app:run()</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Calling a module can be done by using name or call name. The later used for recursive call. Here we use it for beautify the code.
Calling a module can be done by using name or call name. The later used for recursive call. Here we use it for beautify the code.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Module Bars {
Module Bars {
Line 1,204: Line 1,397:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
with(plottools):
with(plottools):
plots:-display([rectangle([0, 0], [.3, 2.1], color = black), rectangle([.3, 0], [.6, 2.1], color = red), rectangle([.6, 0], [.9, 2.1], color = green), rectangle([.9, 0], [1.2, 2.1], color = magenta), rectangle([1.2, 0], [1.5, 2.1], color = cyan), rectangle([1.5, 0], [1.8, 2.1], color = white), rectangle([1.8, 0], [2.1, 2.1], color = yellow)])
plots:-display([rectangle([0, 0], [.3, 2.1], color = black), rectangle([.3, 0], [.6, 2.1], color = red), rectangle([.6, 0], [.9, 2.1], color = green), rectangle([.9, 0], [1.2, 2.1], color = magenta), rectangle([1.2, 0], [1.5, 2.1], color = cyan), rectangle([1.5, 0], [1.8, 2.1], color = white), rectangle([1.8, 0], [2.1, 2.1], color = yellow)])
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==


<lang mathematica>ArrayPlot[
<syntaxhighlight lang="mathematica">ArrayPlot[
ConstantArray[{Black, Red, Green, Blue, Magenta, Cyan, Yellow,
ConstantArray[{Black, Red, Green, Blue, Magenta, Cyan, Yellow,
White}, 5]]</lang>
White}, 5]]</syntaxhighlight>


[[File:ColourBarsMathematica.png]]
[[File:ColourBarsMathematica.png]]
Line 1,222: Line 1,415:
=={{header|Nim}}==
=={{header|Nim}}==
{{libheader|gintro}}
{{libheader|gintro}}
<lang Nim>import gintro/[glib, gobject, gtk, gio, cairo]
<syntaxhighlight lang="nim">import gintro/[glib, gobject, gtk, gio, cairo]


const
const
Line 1,279: Line 1,472:
let app = newApplication(Application, "Rosetta.ColorBars")
let app = newApplication(Application, "Rosetta.ColorBars")
discard app.connect("activate", activate)
discard app.connect("activate", activate)
discard app.run()</lang>
discard app.run()</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>open Graphics
<syntaxhighlight lang="ocaml">open Graphics


let round x =
let round x =
Line 1,302: Line 1,495:
) colors;
) colors;
ignore (read_key ());
ignore (read_key ());
;;</lang>
;;</syntaxhighlight>


execute with:
execute with:
Line 1,308: Line 1,501:


=={{header|Perl}}==
=={{header|Perl}}==
<syntaxhighlight lang="perl">use strict;
<lang Perl>#!/usr/bin/perl -w
use strict ;
use warnings;
use GD ;
use GD;


my %colors = ( white => [ 255 , 255 , 255 ] , red => [255 , 0 , 0 ] ,
my %colors = (
green => [ 0 , 255 , 0 ] , blue => [ 0 , 0 , 255 ] ,
white => [255,255,255], red => [255, 0, 0], green => [ 0,255, 0], blue => [ 0, 0,255],
magenta => [ 255 , 0 , 255 ] , yellow => [ 255 , 255 , 0 ] ,
magenta => [255, 0,255], yellow => [255,255, 0], cyan => [ 0,255,255], black => [ 0, 0, 0]);

cyan => [ 0 , 255 , 255 ] , black => [ 0 , 0 , 0 ] ) ;
my $barwidth = 160 / 8 ;
my $start = 0;
my $image = new GD::Image( 160 , 100 ) ;
my $barwidth = 160 / 8;
my $start = 0 ;
my $image = GD::Image->new( 160 , 100 );

foreach my $rgb ( values %colors ) {
for my $rgb ( values %colors ) {
my $paintcolor = $image->colorAllocate( @$rgb ) ;
$image->filledRectangle( $start * $barwidth , 0 , $start * $barwidth +
$image->filledRectangle( $start * $barwidth , 0 , $start * $barwidth +
$barwidth - 1 , 99 , $paintcolor ) ;
$barwidth - 1 , 99 , $image->colorAllocate( @$rgb ) );
$start++ ;
$start++ ;
}
}
open ( DISPLAY , ">" , "testprogram.png" ) || die ;
open ( DISPLAY , ">" , "bars.png" ) or die;
binmode DISPLAY ;
binmode DISPLAY;
print DISPLAY $image->png ;
print DISPLAY $image->png;
close DISPLAY ;#to be watched with <image viewer> testprogram.png</lang>
close DISPLAY;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
{{libheader|Phix/pGUI}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>-- demo\rosetta\Colour_bars.exw
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Colour_bars.exw</span>
include pGUI.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>

<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
constant colours = {CD_BLACK, CD_RED, CD_GREEN, CD_BLUE, CD_MAGENTA, CD_CYAN, CD_YELLOW, CD_WHITE}

<span style="color: #008080;">constant</span> <span style="color: #000000;">colours</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #004600;">CD_BLACK</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_RED</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_GREEN</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_BLUE</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_MAGENTA</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_CYAN</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_YELLOW</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_WHITE</span><span style="color: #0000FF;">}</span>
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span>

<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cdcanvas</span>
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
cdCanvasActivate(cddbuffer)
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posx*/</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">/*posy*/</span><span style="color: #0000FF;">)</span>
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">),</span>
integer x = 0, lc = length(colours)
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">lc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">colours</span><span style="color: #0000FF;">)</span>
for i=1 to lc do
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
integer w = floor((width-x)/(lc-i+1))
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">lc</span> <span style="color: #008080;">do</span>
cdCanvasSetForeground(cddbuffer, colours[i])
<span style="color: #004080;">integer</span> <span style="color: #000000;">w</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">width</span><span style="color: #0000FF;">-</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)/(</span><span style="color: #000000;">lc</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))</span>
cdCanvasBox(cddbuffer, x, x+w, 0, height)
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">colours</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
x += w
<span style="color: #7060A8;">cdCanvasBox</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000000;">x</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">w</span>
cdCanvasFlush(cddbuffer)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return IUP_DEFAULT
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>

<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"RASTERSIZE=600x400"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- initial size</span>
return IUP_DEFAULT
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="Colour bars"`</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #7060A8;">IupMap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>

<span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
function unmap_cb(Ihandle /*ih*/)
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
cdKillCanvas(cddbuffer)
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- release the minimum limitation</span>
cdKillCanvas(cdcanvas)
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
return IUP_DEFAULT
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
end function
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>

<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
procedure main()
<!--</syntaxhighlight>-->
IupOpen()

canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "600x400") -- initial size

IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "UNMAP_CB", Icallback("unmap_cb"))

dlg = IupDialog(canvas)
IupSetAttribute(dlg, "TITLE", "Colour bars")
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
IupCloseOnEscape(dlg)

IupMap(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation

IupShowXY(dlg,IUP_CENTER,IUP_CENTER)

IupMainLoop()

IupClose()
end procedure

main()</lang>


=={{header|PHP}}==
=={{header|PHP}}==
{{trans|Perl}}
{{trans|Perl}}
Will output result directly to the browser. Use it as CGI/BIN script.
Will output result directly to the browser. Use it as CGI/BIN script.
<lang PHP><?php
<syntaxhighlight lang="php"><?php
$colors = array(array( 0, 0, 0), // black
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array(255, 0, 0), // red
Line 1,419: Line 1,589:
header('Content-type:image/png');
header('Content-type:image/png');
imagepng($image);
imagepng($image);
imagedestroy($image);</lang>
imagedestroy($image);</syntaxhighlight>


Alternately, with HTML output:
Alternately, with HTML output:


<lang PHP><?php
<syntaxhighlight lang="php"><?php
$colors = array(
$colors = array(
"000000", // black
"000000", // black
Line 1,439: Line 1,609:
echo '<td style="background-color: #'.$color.'; height: 100px; width: 20px;"></td>';
echo '<td style="background-color: #'.$color.'; height: 100px; width: 20px;"></td>';
}
}
echo '</tr></table>';</lang>
echo '</tr></table>';</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
{{trans|UNIX Shell}}
{{trans|UNIX Shell}}
<lang PicoLisp>(call 'clear)
<syntaxhighlight lang="picolisp">(call 'clear)


(let Width (in '(tput cols) (read))
(let Width (in '(tput cols) (read))
Line 1,452: Line 1,622:
(prinl) ) )
(prinl) ) )


(call 'tput 'sgr0) # reset</lang>
(call 'tput 'sgr0) # reset</syntaxhighlight>


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Clear the screen.
Clear the screen.
Line 1,483: Line 1,653:
Draw the bar using the cyan color and move it over.
Draw the bar using the cyan color and move it over.
Draw the bar using the yellow color and move it over.
Draw the bar using the yellow color and move it over.
Draw and fill the bar using the white color.</lang>
Draw and fill the bar using the white color.</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
[string[]]$colors = "Black" , "DarkBlue" , "DarkGreen" , "DarkCyan",
[string[]]$colors = "Black" , "DarkBlue" , "DarkGreen" , "DarkCyan",
"DarkRed" , "DarkMagenta", "DarkYellow", "Gray",
"DarkRed" , "DarkMagenta", "DarkYellow", "Gray",
Line 1,501: Line 1,671:
Write-Host
Write-Host
}
}
</syntaxhighlight>
</lang>


=={{header|Processing}}==
=={{header|Processing}}==
<lang processing>fullScreen();
<syntaxhighlight lang="processing">fullScreen();
noStroke();
noStroke();
color[] cs = {
color[] cs = {
Line 1,518: Line 1,688:
fill(cs[i]);
fill(cs[i]);
rect(i*width/8,0,width/8,height);
rect(i*width/8,0,width/8,height);
}</lang>
}</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<syntaxhighlight lang="python">
<lang Python>
#!/usr/bin/env python
#!/usr/bin/env python
#vertical coloured stripes in window in Python 2.7.1
#vertical coloured stripes in window in Python 2.7.1
Line 1,541: Line 1,711:


end_graphics()
end_graphics()
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
Create the color palette, set margins to zero so the image will fill the display, and use image to create the graphic:
Create the color palette, set margins to zero so the image will fill the display, and use image to create the graphic:
[[File:ColorBarR.png|thumb|right]]
[[File:ColorBarR.png|thumb|right]]
<syntaxhighlight lang="r">
<lang R>
pal <- c("black", "red", "green", "blue", "magenta", "cyan", "yellow", "white")
pal <- c("black", "red", "green", "blue", "magenta", "cyan", "yellow", "white")
par(mar = rep(0, 4))
par(mar = rep(0, 4))
image(matrix(1:8), col = pal, axes = FALSE)
image(matrix(1:8), col = pal, axes = FALSE)
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket/gui
#lang racket/gui


Line 1,579: Line 1,749:


(void (new full-frame%))
(void (new full-frame%))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2018.10}}
{{works with|Rakudo|2018.10}}
<lang perl6>my ($x,$y) = 1280, 720;
<syntaxhighlight lang="raku" line>my ($x,$y) = 1280, 720;


my @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $x div 8) },
my @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $x div 8) },
Line 1,611: Line 1,781:
}
}


$img.close;</lang>
$img.close;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,622: Line 1,792:
Programming note: &nbsp; because of the way the REXX interpreters &nbsp; (being used for this example) &nbsp; ensure screen output fidelity, &nbsp; if ninety characters are displayed on a ninety-byte wide screen, &nbsp; REXX apparently forces an extra blank, &nbsp; causing to what appears to be a blank line after the line displayed. &nbsp; Because of this, &nbsp; the last color bar &nbsp; ('''_.8''') &nbsp; has been shortened by one byte.
Programming note: &nbsp; because of the way the REXX interpreters &nbsp; (being used for this example) &nbsp; ensure screen output fidelity, &nbsp; if ninety characters are displayed on a ninety-byte wide screen, &nbsp; REXX apparently forces an extra blank, &nbsp; causing to what appears to be a blank line after the line displayed. &nbsp; Because of this, &nbsp; the last color bar &nbsp; ('''_.8''') &nbsp; has been shortened by one byte.


<lang rexx>/*REXX program displays eight colored vertical bars on a full screen. */
<syntaxhighlight lang="rexx">/*REXX program displays eight colored vertical bars on a full screen. */
parse value scrsize() with sd sw . /*the screen depth and width. */
parse value scrsize() with sd sw . /*the screen depth and width. */
barWidth=sw%8 /*calculate the bar width. */
barWidth=sw%8 /*calculate the bar width. */
Line 1,647: Line 1,817:
say $ /*have REXX display line of bars. */
say $ /*have REXX display line of bars. */
end /*k*/ /* [↑] Note: SD could be zero. */
end /*k*/ /* [↑] Note: SD could be zero. */
/*stick a fork in it, we're done. */</lang>
/*stick a fork in it, we're done. */</syntaxhighlight>
This REXX program makes use of &nbsp; '''scrsize''' &nbsp; REXX program (or BIF) which is used to determine the screen size of the terminal (console).
This REXX program makes use of &nbsp; '''scrsize''' &nbsp; REXX program (or BIF) which is used to determine the screen size of the terminal (console).


Line 1,655: Line 1,825:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "guilib.ring"
load "guilib.ring"


Line 1,715: Line 1,885:
}
}
label1 { setpicture(p1) show() }
label1 { setpicture(p1) show() }
</syntaxhighlight>
</lang>
Output :
Output :
[https://lh3.googleusercontent.com/-_y0FSmg0NAs/V1xBPvGV2tI/AAAAAAAAAKk/TXYSJnpdZ346aQLd05yE9vLM8V9lEht1QCLcB/s1600/CalmoSoftColourBars.jpg Colour bars]
[https://lh3.googleusercontent.com/-_y0FSmg0NAs/V1xBPvGV2tI/AAAAAAAAAKk/TXYSJnpdZ346aQLd05yE9vLM8V9lEht1QCLcB/s1600/CalmoSoftColourBars.jpg Colour bars]
Line 1,723: Line 1,893:
{{libheader|JRubyArt}}
{{libheader|JRubyArt}}
JRubyArt is a port of Processing to the ruby language
JRubyArt is a port of Processing to the ruby language
<lang ruby>
<syntaxhighlight lang="ruby">
# Array of web colors black, red, green, blue, magenta, cyan, yellow, white
# Array of web colors black, red, green, blue, magenta, cyan, yellow, white
PALETTE = %w[#000000 #ff0000 #00ff00 #0000ff #ff00ff #00ffff #ffffff].freeze
PALETTE = %w[#000000 #ff0000 #00ff00 #0000ff #ff00ff #00ffff #ffffff].freeze
Line 1,737: Line 1,907:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Rust}}==
=={{header|Rust}}==
Line 1,743: Line 1,913:
{{libheader|pixels}}
{{libheader|pixels}}
renders into a borderless fullscreen window on the primary display. press ESC to close
renders into a borderless fullscreen window on the primary display. press ESC to close
<lang rust>use pixels::{Pixels, SurfaceTexture}; // 0.2.0
<syntaxhighlight lang="rust">use pixels::{Pixels, SurfaceTexture}; // 0.2.0
use winit::event::*; // 0.24.0
use winit::event::*; // 0.24.0
use winit::event_loop::{ControlFlow, EventLoop};
use winit::event_loop::{ControlFlow, EventLoop};
Line 1,789: Line 1,959:
}
}
});
});
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>import java.awt.Color
<syntaxhighlight lang="scala">import java.awt.Color
import scala.swing._
import scala.swing._


Line 1,807: Line 1,977:
}
}
}
}
}</lang>
}</syntaxhighlight>
Open window:
Open window:
[[File:colorbars_scala.png|thumb|right]]
[[File:colorbars_scala.png|thumb|right]]
<lang scala>new MainFrame(){
<syntaxhighlight lang="scala">new MainFrame(){
title="Color bars"
title="Color bars"
visible=true
visible=true
preferredSize=new Dimension(640, 320)
preferredSize=new Dimension(640, 320)
contents=new ColorBars()
contents=new ColorBars()
}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>require('GD');
<syntaxhighlight lang="ruby">require('GD');


var colors = Hash.new(
var colors = Hash.new(
Line 1,842: Line 2,012:
};
};


%f'colorbars.png'.open('>:raw').print(image.png);</lang>
%f'colorbars.png'.open('>:raw').print(image.png);</syntaxhighlight>

=={{header|SmileBASIC}}==
<lang smilebasic>FOR I=0 TO 7
READ R,G,B
GFILL I*50,0,I*50+49,239,RGB(R,G,B)
NEXT
REPEAT UNTIL BUTTON(0) AND #B

DATA 0,0,0
DATA 255,0,0
DATA 0,255,0
DATA 0,0,255
DATA 255,0,255
DATA 0,255,255
DATA 255,255,0
DATA 255,255,255</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
{{libheader|Tk}}
{{libheader|Tk}}
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require Tk 8.5
package require Tk 8.5


Line 1,873: Line 2,027:
-fill [lindex $colors 0] -outline {}
-fill [lindex $colors 0] -outline {}
set colors [list {*}[lrange $colors 1 end] [lindex $colors 0]]
set colors [list {*}[lrange $colors 1 end] [lindex $colors 0]]
}</lang>
}</syntaxhighlight>


== {{header|UNIX Shell}} ==
=={{header|UNIX Shell}}==
<lang sh>#!/bin/sh
<syntaxhighlight lang="sh">#!/bin/sh
clear
clear
WIDTH=`tput cols`
WIDTH=`tput cols`
Line 1,899: Line 2,053:
done
done


tput sgr0 # reset</lang>
tput sgr0 # reset</syntaxhighlight>

=={{header|Uxntal}}==
<syntaxhighlight lang="uxntal">( uxnasm color-bars.tal color-bars.rom && uxnemu color-bars.rom )

|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1
|20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1

|0100
( set 4 color theme
rgb
color0: 000 - black
color1: f00 - red
color2: 0f0 - green
color3: 00f - blue )
#0f00 .System/r DEO2
#00f0 .System/g DEO2
#000f .System/b DEO2

( store bars width )
.Screen/width DEI2 #0004 DIV2 ,&quarter STR2
( set starting position )
#0000 .Screen/y DEO2


( draw bars )
#00
&loop
#00 OVR [ LIT2 &quarter $2 ] MUL2
.Screen/x DEO2
DUP #80 ORA .Screen/pixel DEO
INC DUP #04 NEQ ?&loop
BRK</syntaxhighlight>
[[File:Color-bars.png|alt=Color bars task implemented in Uxntal.|thumb|Color bars task implemented in Uxntal.|none]]
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Go}}
{{trans|Go}}
{{libheader|DOME}}
{{libheader|DOME}}
<lang ecmascript>import "graphics" for Canvas, Color
<syntaxhighlight lang="wren">import "graphics" for Canvas, Color
import "dome" for Window
import "dome" for Window


Line 1,938: Line 2,123:


static draw(dt) {}
static draw(dt) {}
}</lang>
}</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic code declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic code declarations
int W, X0, X1, Y, C;
int W, X0, X1, Y, C;
[SetVid($13); \320x200x8 graphics
[SetVid($13); \320x200x8 graphics
Line 1,952: Line 2,137:
C:= ChIn(1); \wait for keystroke
C:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
SetVid(3); \restore normal text mode
]</lang>
]</syntaxhighlight>


{{omit from|Axe}}
{{omit from|Axe}}
{{omit from|GUISS}}
{{omit from|GUISS}}
{{omit from|Minimal BASIC}}


[[Category:Test card]]
[[Category:Test card]]

Latest revision as of 19:45, 15 March 2024

Task
Colour bars/Display
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Display a series of vertical color bars across the width of the display.

The color bars should either use:

  •   the system palette,   or
  •   the sequence of colors:
  •   black
  •   red
  •   green
  •   blue
  •   magenta
  •   cyan
  •   yellow
  •   white


6502 Assembly

Implemented using Easy6502, this displays a pinstripe using the system palette. There are 16 colors, and the bottom 4 bits of A are the color index.

lda #0
tax
tay        ;clear regs

;video ram on Easy6502 is four pages ranging from $0200-$0500

loop:
sta $0200,x
sta $0220,x
sta $0240,x
sta $0260,x
sta $0280,x
sta $02A0,x
sta $02C0,x
sta $02E0,x

sta $0300,x
sta $0320,x
sta $0340,x
sta $0360,x
sta $0380,x
sta $03A0,x
sta $03C0,x
sta $03E0,x

sta $0400,x
sta $0420,x
sta $0440,x
sta $0460,x
sta $0480,x
sta $04A0,x
sta $04C0,x
sta $04E0,x

sta $0500,x
sta $0520,x
sta $0540,x
sta $0560,x
sta $0580,x
sta $05A0,x
sta $05C0,x
sta $05E0,x

inx
txa      ;effectively increment A
cpx #$20 ;32 columns of video memory
beq exit
jmp loop
exit:
brk       ;on easy6502 this terminates a program.


Action!

PROC Main()
  BYTE
    i,
    CH=$02FC, ;Internal hardware value for last key pressed
    PALNTSC=$D014, ;To check if PAL or NTSC system is used
    PCOLR0=$02C0,PCOLR1=$02C1,
    PCOLR2=$02C2,PCOLR3=$02C3,
    COLOR0=$02C4,COLOR1=$02C5,
    COLOR2=$02C6,COLOR3=$02C7,
    COLOR4=$02C8
  
  Graphics(10)
  PCOLR0=$04 ;gray
  PCOLR1=$00 ;black
  IF PALNTSC=15 THEN
    PCOLR2=$42 ;red for NTSC
    PCOLR3=$C6 ;green for NTSC
    COLOR0=$84 ;blue for NTSC
    COLOR1=$66 ;magenta for NTSC
    COLOR2=$A6 ;cyan for NTSC
    COLOR3=$FC ;yellow for NTSC
  ELSE
    PCOLR2=$22 ;red for PAL
    PCOLR3=$B6 ;green for PAL
    COLOR0=$74 ;blue for PAL
    COLOR1=$48 ;magenta for PAL
    COLOR2=$96 ;cyan for PAL
    COLOR3=$EC ;yellow for PAL
  FI
  COLOR4=$0F ;white

  FOR i=0 TO 79
  DO
    Color=i/10+1
    Plot(i,0)
    DrawTo(i,191)
  OD

  DO UNTIL CH#$FF OD
  CH=$FF
RETURN
Output:

Screenshot from Atari 8-bit computer

ActionScript

package {
    
    import flash.display.Sprite;
    import flash.events.Event;

    public class ColourBars extends Sprite {
        
        public function ColourBars():void {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }
        
        private function init(e:Event = null):void {
            
            var colours:Array = [ 0x000000, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF00FF, 0x00FFFF, 0xFFFF00, 0xFFFFFF ];
            var w:Number = stage.stageWidth / 8, h:Number = stage.stageHeight;
            var x:Number = 0, i:uint, c:uint;
            
            for ( i = 0; i < 8; i++ ) {
                c = colours[i];
                graphics.beginFill(c);
                graphics.drawRect(w * i, 0, w, h);
            }
            
        }
        
    }
    
}

Ada

Library: SDLAda
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Palettes;
with SDL.Events.Events;
with SDL.Events.Keyboards;

procedure Colour_Bars_Display is
   use type SDL.Events.Event_Types;
   use SDL.C;

   Colours : constant array (0 .. 7) of SDL.Video.Palettes.Colour :=
     ((0, 0, 0, 255),     (255, 0, 0, 255),
      (0, 255, 0, 255),   (0, 0, 255, 255),
      (255, 0, 255, 255), (0, 255, 255, 255),
      (255, 255, 0, 255), (255, 255, 255, 255));
   Window    : SDL.Video.Windows.Window;
   Renderer  : SDL.Video.Renderers.Renderer;
   Event     : SDL.Events.Events.Events;
   Bar_Width : int;
begin
   if not SDL.Initialise (Flags => SDL.Enable_Screen) then
      return;
   end if;

   SDL.Video.Windows.Makers.Create (Win      => Window,
                                    Title    => "",
                                    Position => SDL.Natural_Coordinates'(0, 0),
                                    Size     => SDL.Positive_Sizes'(0, 0),
                                    Flags    => SDL.Video.Windows.Full_Screen_Desktop);
   SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);

   Bar_Width := Window.Get_Size.Width / 8;
   for A in Colours'Range loop
      Renderer.Set_Draw_Colour (Colour => Colours (A));
      Renderer.Fill (Rectangle => (X => SDL.C.int (A) * Bar_Width, Y => 0,
                                   Width  => Bar_Width,
                                   Height => Window.Get_Size.Height));
   end loop;
   Window.Update_Surface;

   Wait_Loop : loop
      while SDL.Events.Events.Poll (Event) loop
         exit Wait_Loop when Event.Common.Event_Type = SDL.Events.Keyboards.Key_Down;
      end loop;
      delay 0.050;
   end loop Wait_Loop;
   Window.Finalize;
   SDL.Finalise;
end Colour_Bars_Display;

AutoHotkey

Library: GDI+

(available at http://www.autohotkey.net/~tic/Gdip.ahk)

#SingleInstance, Force
#NoEnv
SetBatchLines, -1
 
; Uncomment if Gdip.ahk is not in your standard library
;#Include, Gdip.ahk
 
; Start gdi+
If !pToken := Gdip_Startup()
{
   message =
   ( LTrim
      gdiplus error!, Gdiplus failed to start.
      Please ensure you have gdiplus on your system.
   )
   MsgBox, 48, %message%
   ExitApp
}
OnExit, Exit

; Set the width and height we want as our drawing area, to draw everything in.
; This will be the dimensions of our bitmap
Width := A_ScreenWidth, Height := A_ScreenHeight
 
; Create a layered window
; (+E0x80000 : must be used for UpdateLayeredWindow to work!)
; that is always on top (+AlwaysOnTop), has no taskbar entry or caption
Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
 
; Show the window
Gui, 1: Show, NA
 
; Get a handle to this window we have created in order to update it later
hwnd1 := WinExist()
 
; Create a gdi bitmap with width and height of what we are going to
; draw into it. This is the entire drawing area for everything
hbm := CreateDIBSection(Width, Height)
 
; Get a device context compatible with the screen
hdc := CreateCompatibleDC()
 
; Select the bitmap into the device context
obm := SelectObject(hdc, hbm)
 
; Get a pointer to the graphics of the bitmap, for use with drawing functions
G := Gdip_GraphicsFromHDC(hdc)
 
; ARGB = Transparency, Red, Green, Blue
Colors := "0xFF000000,0xFFFF0000,0xFF00FF00,0xFF0000FF"
Colors .= ",0xFFFF00FF,0xFF00FFFF,0xFFFFFF00,0xFFFFFFFF"
; This list ^ is Black, Red, Green, Blue, Magenta, Cyan, Yellow, White
StringSplit Colors, Colors, `,
w := Width // Colors0
Loop % Colors0
{
   ; Create a brush to draw a rectangle
   pBrush := Gdip_BrushCreateSolid(Colors%A_Index%)
 
   ; Fill the graphics of the bitmap with a rectangle using the brush created
   Gdip_FillRectangle(G, pBrush, w*(A_Index-1), 0, w, height)
 
   ; Delete the brush as it is no longer needed and wastes memory
   Gdip_DeleteBrush(pBrush)
}
; Update the specified window we have created (hwnd1) with a handle to our
; bitmap (hdc), specifying the x,y,w,h we want it positioned on our screen
; So this will position our gui at (0,0) with the Width and
; Height specified earlier
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
 
 
; Select the object back into the hdc
SelectObject(hdc, obm)
 
; Now the bitmap may be deleted
DeleteObject(hbm)
 
; Also the device context related to the bitmap may be deleted
DeleteDC(hdc)
 
; The graphics may now be deleted
Gdip_DeleteGraphics(G)
Return
 
;#######################################################################
 
GuiEscape:
Exit:
; gdi+ may now be shutdown on exiting the program
Gdip_Shutdown(pToken)
ExitApp
Return

AWK

BEGIN {
  nrcolors = 8

  for (height=0; height<20; height++) {
    for (width=0; width<nrcolors; width++) {
      # print (ANSI) basic color and amount of spaces
      printf("\033[%dm%*s", width + 40, 64 / nrcolors, " ")
    }
    
    # reset color and print newline
    printf("\033[0m\n")
  }
}

BASIC

AmigaBASIC

SCREEN 1,320,200,5,1
WINDOW 2,"Color bars",(0,10)-(297,186),15,1
FOR a=0 TO 300
  LINE (a,0)-(a,186),(a+10)/10
NEXT
loop: GOTO loop

Applesoft BASIC

1 DATA1,12,6,3,14,13,15
2 HOME : GR : FOR I = 1 TO 7
3                 READ C(I) : NEXT
4 FOR I = 0 TO 39
5     COLOR= C(I / 5)
6     VLIN 0,39 AT I : NEXT

BBC BASIC

      SW_MAXIMIZE = 3
      SYS "ShowWindow", @hwnd%, SW_MAXIMIZE
      VDU 26
      
      W% = @vdu%!208 / 4
      H% = @vdu%!212 * 2
      
      COLOUR 1,9
      COLOUR 2,10
      COLOUR 3,12
      COLOUR 4,13
      COLOUR 5,14
      COLOUR 6,11
      COLOUR 7,15
      
      FOR C% = 0 TO 7
        GCOL C%
        RECTANGLE FILL C%*W%, 0, W%, H%
      NEXT

Chipmunk Basic

The sequence of colors.

100 rem Colour bars/Display
110 graphics 0 : graphics cls
120 for i = 0 to 7
130   read r,g,b
140   graphics color r,g,b
150   for j = 0 to 79
160     x = i*80+j
170     graphics moveto x,0
180     graphics lineto x,399
190   next j
200 next i
500 data 0,0,0 : rem black
510 data 100,0,0 : rem red
520 data 0,100,0 : rem green
530 data 0,0,100 : rem blue
540 data 100,0,100 : rem magenta
550 data 0,100,100 : rem cyan
560 data 100,100,0 : rem yellow
570 data 100,100,100 : rem white

Commodore BASIC

This task achieved only on Commodore computers with color capabilities. The example below tested as-is in VICE on the following machines:

  • Commodore 64
  • Commodore 128
  • Commodore Plus 4
  • Commodore CBM-II (with VIC-II video)
  • Commodore SX-64

It will also work well on the VIC-20 if you either omit line 310 or comment (REM) it out as the VIC-20 has only an eight-color palette.

This cross-compatibility is achieved by using the PETSCII control codes (CHR$(x)) for changing color, which are generally the same across all platforms, although the system palettes themselves may differ. This is combined with printing a "reverse video" space (solid block) character in the color selected.

5 rem color bars program
10 print chr$(147);:dim co(17):c=1
20 read co(c):if co(c)>0 then c=c+1:goto 20
25 sp$="     ":h=22:c=c-1:rem sp$=5 spaces
30 for r=1 to c step int(c/2)
40 for h=1 to 10
50 for b=r to (r+int(c/2))-1
60 print chr$(18);chr$(co(b));sp$;
70 next b
75 rem check if palette is only 8 (vic-20). 
76 rem if so, we need to fill the last two spaces.
80 if c<=8 then print "  ";
90 next h:next r
100 get k$:if k$="" then 100
110 end
280 rem because the control codes for color are non-sequential,
285 rem we put them into a sequential array for use
300 data 144,5,28,159,156,30,31,158
305 rem omit or rem the next line for vic-20
310 data 129,149,150,151,152,153,154,155
320 data 0:rem data terminato

FreeBASIC

' FB 1.05.0 Win64

' Draw the color bars on an 80 x 25 console using the system palette of 16 colors
' i.e. 5 columns per color
Width 80, 25
Shell "cls"
Locate ,, 0  '' turn cursor off
For clr As UInteger = 0 To 15
  Color 0, clr
  For row As Integer = 1 to 25
    Locate row, clr * 5 + 1 
    Print Space(5);
  Next row
Next clr

Sleep
' restore default settings
Locate ,, 1 '' turn cursor on
Color 7, 0  '' white text on black background

FutureBasic

void local fn DoIt
  long index, x = 0
  CFArrayRef colors = @[fn ColorBlack,fn ColorRed,
  fn ColorGreen,fn ColorBlue,fn ColorMagenta,
  fn ColorCyan,fn ColorYellow,fn ColorWhite]
  
  window 1, @"Color bars/Display", (0,0,480,270), NSWindowStyleMaskTitled
  
  pen -1
  for index = 0 to len(colors) - 1
    rect fill (x,0,60,270), colors[index]
    x += 60
  next
end fn

fn DoIt

HandleEvents

Gambas

Public Sub Form_Open()
Dim iColour As Integer[] = [Color.Black, Color.red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.white]
Dim hPanel As Panel
Dim siCount As Short

With Me
  .Arrangement = Arrange.Horizontal
  .Height = 300
  .Width = 400
End With

For siCount = 0 To 6
  hpanel = New Panel(Me)
  hpanel.Expand = True
  hpanel.H = 500
  HPanel.Background = iColour[siCount]
Next

End

IS-BASIC

100 GRAPHICS LORES 16
110 SET PALETTE BLACK,RED,GREEN,BLUE,MAGENTA,CYAN,YELLOW,WHITE
120 FOR I=1 TO 7
130   CALL BAR(I)
140 NEXT 
150 DEF BAR(C)
160   SET INK C
170   PLOT C*160,0;C*160,719;C*160+152,719;C*160+152,0;C*160,0
180   PLOT C*160+16,16,PAINT
190 END DEF

Liberty BASIC

nomainwin
colors$="black red green blue pink cyan yellow white"
WindowWidth=DisplayWidth:WindowHeight=DisplayHeight
UpperLeftX=1:UpperLeftY=1
barWidth=DisplayWidth/8
graphicbox #main.g, 0,0,DisplayWidth,DisplayHeight
open "" for window_popup as #main
#main "trapclose [quit]"
#main.g "down; setfocus; when characterInput [quit]"
#main.g "when leftButtonUp [quit]"
#main.g "size ";barWidth

for x = barWidth/2 to DisplayWidth step barWidth
    i=i+1
    if i>8 then i=1
    col$=word$(colors$,i)
    #main.g "color ";col$;"; line ";x;" 0 ";x;" ";DisplayHeight
next
wait
[quit] close #main:end

Locomotive Basic

Show the default MODE 0 palette (includes two blinking colors at the end):

10 MODE 0:BORDER 23
20 FOR x=0 TO 15
30 ORIGIN x*40,0
40 FOR z=0 TO 39 STEP 4:MOVE z,0:DRAW z,400,x:NEXT z
50 NEXT x
60 CALL &bb06 ' wait for key press

PureBasic

Press Enter or Escape to exit the program.

Dim color(7)
color(0) = RGB($00, $00, $00) ;black
color(1) = RGB($FF, $00, $00) ;red
color(2) = RGB($00, $FF, $00) ;green
color(3) = RGB($00, $00, $FF) ;blue
color(4) = RGB($FF, $00, $FF) ;magenta
color(5) = RGB($00, $FF, $FF) ;cyan
color(6) = RGB($FF, $FF, $00) ;yellow
color(7) = RGB($FF, $FF, $FF) ;white 

If Not InitKeyboard(): End: EndIf    ;can't init keyboard
If Not InitSprite(): End: EndIf      ;can't init sprite/screen library
If Not ExamineDesktops(): End: EndIf ;can't retrieve information about desktop

height = DesktopHeight(0)
width = DesktopWidth(0)
depth = DesktopDepth(0)
If OpenScreen(width, height, depth, "Press ENTER to exit")
  StartDrawing(ScreenOutput())
    For c = 0 To 7
      Box((width * c) / 8, 0, width / 8, height, color(c))
    Next
  StopDrawing()
  FlipBuffers()

  Repeat
    Delay(10)
    ExamineKeyboard()
  Until KeyboardPushed(#PB_Key_Escape) Or KeyboardPushed(#PB_Key_Return)
  CloseScreen()
EndIf

Alternate method using console

DataSection
  ;Black, Red, Green, Blue, Magenta, Cyan, Yellow, White
  Data.i  0, 12, 10, 9, 13, 11, 14, 15
EndDataSection

Dim colors(7)
For c = 0 To 7
  Read.i colors(c)
Next 

If OpenConsole()
  ;The console display is 80 columns wide by 25 rows
  For r = 0 To 24
    For c = 0 To 7 
      ConsoleColor(colors(c), colors(c))
      Print(Space(80 / 8))
    Next
  Next
  EnableGraphicalConsole(1)
  ConsoleLocate(0, 0)
  
  ConsoleTitle("Press ENTER to exit"): Input()
  CloseConsole()
EndIf

Run BASIC

colors$ = "black,red,green,blue,magenta,cyan,yellow,white"
html "<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=4><tr height=70>"
for i = 1 to 8
  html "<td width=20 bgcolor='";word$(colors$,i,",");"'</td>"
next i
html "</tr></table>"
Output

SmileBASIC

FOR I=0 TO 7
 READ R,G,B
 GFILL I*50,0,I*50+49,239,RGB(R,G,B)
NEXT
REPEAT UNTIL BUTTON(0) AND #B

DATA 0,0,0
DATA 255,0,0
DATA 0,255,0
DATA 0,0,255
DATA 255,0,255
DATA 0,255,255
DATA 255,255,0
DATA 255,255,255

TI Basic

100 REM  SMPTE Format Color Bars
110 REM  with 400 Hz reference tone
120 CALL CLEAR
130 CALL SCREEN(2)
140 CALL COLOR(8,15,1)
150 CALL COLOR(9,11,1)
160 CALL COLOR(10,8,1)
170 CALL COLOR(11,13,1)
180 CALL COLOR(12,14,1)
190 CALL COLOR(13,10,1)
200 CALL COLOR(14,5,1)
210 CALL COLOR(15,2,1)
220 CALL COLOR(16,16,1)
230 GOSUB 510
240 REM  color bars
250 CALL VCHAR(1,3,88,96)
260 CALL VCHAR(1,7,96,96)
270 CALL VCHAR(1,11,104,96)
280 CALL VCHAR(1,15,112,96)
290 CALL VCHAR(1,19,120,96)
300 CALL VCHAR(1,23,128,96)
310 CALL VCHAR(1,27,136,96)
320 REM  BLACK BAR
330 CALL HCHAR(19,1,144,224)
340 REM  WHITE BOX
350 FOR I=19 TO 24
360 CALL HCHAR(I,8,152,6)
370 NEXT I
410 REM  SMPTE Complementary boxes
420 CALL HCHAR(18,3,136,4)
430 CALL HCHAR(18,7,144,4)
440 CALL HCHAR(18,11,120,4)
450 CALL HCHAR(18,15,144,4)
460 CALL HCHAR(18,19,104,4)
470 CALL HCHAR(18,23,144,4)
480 CALL HCHAR(18,27,88,4)
490 CALL SOUND(3000,400,12)
500 GOTO 490
510 SQUARE$="FFFFFFFFFFFFFFFF"
520 FOR I = 88 TO 152 STEP 8
530 CALL CHAR(I,SQUARE$)
540 NEXT I
590 RETURN

ZX Spectrum Basic

10 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces
20 FOR r=0 TO 20: REM There are 21 rows
30 FOR c=0 TO 7: REM We use the native colour sequence here
40 PAPER c: REM set the background colour for the spaces to be printed
50 PRINT "    ";: REM four spaces, the semicolon prevents newline
60 NEXT c
70 REM at this point the cursor has wrapped, so we don't need a newline
80 NEXT r

Befunge

Assuming a terminal with support for ANSI escape sequences, this fills the screen with the colour sequence: black, red, green, blue, magenta, cyan, yellow and white. It then waits for the user to press Enter before terminating.

<v%"P":          <<*"(2"
v_:"P"/"["39*,, :55+/68v
v,,,";1H" ,+*86%+55 ,+*<
73654210v,,\,,,*93"[4m"<
>$:55+%#v_:1-"P"%55+/3g^
39*,,,~@>48*,1-:#v_$"m["

C

This task requires functionality which allows the code to communicate to the video device. This will vary from vendor to vendor. The following examples show two ways of doing this, in the text and graphics mode, using Borland's Turbo C.

Text Mode

The required functions and structures are in conio.h

#include<conio.h>

#define COLOURS 8

int main()
{
	int colour=0,i,j,MAXROW,MAXCOL;
	struct text_info tInfo;
	gettextinfo(&tInfo);
	MAXROW = tInfo.screenheight;
	MAXCOL = tInfo.screenwidth;
	textbackground(BLACK);     //8 colour constants are defined
	clrscr();
	
	for(colour=0;colour<COLOURS;colour++)
	{
		getch();                              //waits for a key hit
		gotoxy(1+colour*MAXCOL/COLOURS,1);
		textbackground(colour);
		for(j=0;j<MAXROW;j++){
			for(i=0;i<MAXCOL/COLOURS;i++){
				cprintf(" ");
			}
		gotoxy(1+colour*MAXCOL/COLOURS,1+j);
		}
	}

	getch();
	textbackground(BLACK);

	return 0;
}

Graphics Mode

The required functions and structures are in graphics.h, conio.h is included for getch().

#include<graphics.h>
#include<conio.h>

int main()
{
	int d=DETECT,m,maxX,maxY,maxColours,i;
	initgraph(&d,&m,"c:/turboc3/bgi");
	maxX = getmaxx();
	maxY = getmaxy();
	maxColours = getmaxcolor();

	for(i=0;i<maxColours;i++)
	{
		setfillstyle(SOLID_FILL,i);
		bar(i*maxX/maxColours,0,(i+1)*maxX/maxColours,maxY);
	}

	getch();
	closegraph();
	
	return 0;
}

C++

using Qt 4.6

file colorbars.h:

#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>

class QPaintEvent ;

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

protected :
   void paintEvent( QPaintEvent * ) ;
private :
   int width ;
   int height ;
   const int colornumber ;
} ;
#endif

file colorbars.cpp:

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

MyWidget::MyWidget( ) :
   width( 640 ) ,
   height( 240 ) ,
   colornumber( 8 ) {
      setGeometry( 0, 0 , width , height ) ;
}

void MyWidget::paintEvent ( QPaintEvent * ) {
   int rgbtriplets[ ] = { 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 0 , 
      0 , 0 , 255 , 255 , 0 , 255 , 0 , 255 , 255 , 255 , 255 , 0 ,
      255 , 255 , 255 } ; 
   QPainter myPaint( this ) ;
   int rectwidth = width / colornumber ; //width of one rectangle
   int xstart = 1 ; //x coordinate of the first rectangle
   int offset = -1  ; //to allow for ++offset to define the red value even in the first run of the loop below
   for ( int i = 0 ; i < colornumber ; i++ ) {
      QColor rectColor ;
      rectColor.setRed( rgbtriplets[ ++offset ] ) ;
      rectColor.setGreen( rgbtriplets[ ++offset ] ) ;
      rectColor.setBlue( rgbtriplets[ ++offset ] ) ;
      myPaint.fillRect( xstart , 0 , rectwidth , height - 1 , rectColor ) ;
      xstart += rectwidth + 1 ;
   }
}

file main.cpp:

#include <QApplication>
#include "colorbars.h"

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

COBOL

Works with: OpenCOBOL
       IDENTIFICATION DIVISION.
       PROGRAM-ID. terminal-colour-bars.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  width           PIC 9(3).
       01  height          PIC 9(3).

       01  interval        PIC 9(3).

       01  colours-area.
           03  colour-values.
               05  FILLER  PIC 9 VALUE 0. *> Black
               05  FILLER  PIC 9 VALUE 4. *> Red
               05  FILLER  PIC 9 VALUE 2. *> Green
               05  FILLER  PIC 9 VALUE 1. *> Blue
               05  FILLER  PIC 9 VALUE 5. *> Magneta
               05  FILLER  PIC 9 VALUE 3. *> Cyan
               05  FILLER  PIC 9 VALUE 6. *> Yellow
               05  FILLER  PIC 9 VALUE 7. *> White

           03  colour-table REDEFINES colour-values.
               05  colours PIC 9 OCCURS 8 TIMES INDEXED BY colour-index.

       01  i               PIC 9(3).
       01  j               PIC 9(3).

       PROCEDURE DIVISION.
           ACCEPT width FROM COLUMNS
           ACCEPT height FROM LINES
           DIVIDE width BY 8 GIVING interval

           PERFORM VARYING i FROM 1 BY 1 UNTIL height < i
               PERFORM VARYING j FROM 1 BY 1 UNTIL width < j
                  COMPUTE colour-index = (j / interval) + 1
                  
                  IF 8 < colour-index
                      SET colour-index TO 8
                  END-IF

                  *> Some colours come a bit darker than they
                  *> should, with the yellow being orange and the white
                  *> being light-grey.
                  DISPLAY SPACE AT LINE i COLUMN j
                      WITH BACKGROUND-COLOR colours (colour-index)
               END-PERFORM
           END-PERFORM

           ACCEPT i *> Prevent ncurses returning to console immediately.

           GOBACK
           .

Common Lisp

ncurses

To interface the ncurses C library from Lisp, the croatoan library is used.

(defun color-bars ()
  (with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
    (dotimes (i (height scr))
      (move scr i 0)
      (dolist (color '(:red :green :yellow :blue :magenta :cyan :white :black))
        (add-char scr #\space :bgcolor color :n (floor (/ (width scr) 8)))))
    (refresh scr)
    ;; wait for keypress
    (get-char scr)))

Delphi

Library: Vcl.Forms
unit Colour_barsDisplay;

interface

uses
  Winapi.Windows,  System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms;

type
  TfmColourBar = class(TForm)
    procedure FormPaint(Sender: TObject);
    procedure FormResize(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  fmColourBar: TfmColourBar;
  Colors: array of TColor = [clblack, clred, clgreen, clblue, clFuchsia, clAqua,
    clyellow, clwhite];

implementation

{$R *.dfm}

procedure TfmColourBar.FormPaint(Sender: TObject);
var
  w, h, i: Integer;
  r: TRect;
begin
  w := ClientWidth div length(Colors);
  h := ClientHeight;
  r := Rect(0, 0, w, h);

  with Canvas do
    for i := 0 to High(Colors) do
    begin
      Brush.Color := Colors[i];
      FillRect(r);
      r.Offset(w, 0);
    end;
end;

procedure TfmColourBar.FormResize(Sender: TObject);
begin
 Invalidate;
end;
end.

Form resource:

object fmColourBar: TfmColourBar
  Caption = 'fmColourBar'
  OldCreateOrder = False
  OnPaint = FormPaint
  OnResize = FormResize
end

EasyLang

Run it

col[] = [ 000 900 090 009 909 099 990 999 ]
w = 100 / len col[]
for i = 1 to len col[]
   color col[i]
   move w * (i - 1) 0
   rect w 100
.

Factor

USING: accessors colors.constants kernel math sequences ui
ui.gadgets ui.gadgets.tracks ui.pens.solid ;
IN: rosetta-code.colour-bars-display

: colors ( -- ) [
horizontal <track>
{
 COLOR: black
 COLOR: red
 COLOR: green
 COLOR: blue
 COLOR: magenta
 COLOR: cyan
 COLOR: yellow
 COLOR: white
}
[ <solid> gadget new swap >>interior ] map
dup length recip
[ track-add ] curry each
{ 640 480 } >>pref-dim
"bars" open-window
] with-ui ;
MAIN: colors

Forth

This program extends ANS Forth to control the TMS9918 Video display processor in the TI-99 computer.
The color bars are shown in Society of Motion Picture and Television Engineers (SMPTE) order.

\ Color Bars for TI-99 CAMEL99 Forth

NEEDS HCHAR   FROM DSK1.GRAFIX    \ TMS9918 control lexicon
NEEDS CHARSET FROM DSK1.CHARSET   \ restores default character data
NEEDS ENUM    FROM DSK1.ENUM      \ add simple enumerator to Forth

\ Name TI-99 colors
1 ENUM CLR     ENUM BLK    ENUM MGRN   ENUM LGRN
  ENUM BLU     ENUM LBLU   ENUM RED    ENUM CYAN
  ENUM MRED    ENUM LRED   ENUM YEL    ENUM LYEL
  ENUM GRN     ENUM MAG    ENUM GRY    ENUM WHT
DROP

\ square character data
HEX
CREATE SQUARE  FFFF , FFFF , FFFF , FFFF ,

DECIMAL
: COLOR-BARS ( -- )
   24 0 DO
\   col row char wid
\   --- --- ---- ---
      2  I   88   4 HCHAR
      6  I   96   4 HCHAR
     10  I  104   4 HCHAR
     14  I  112   4 HCHAR
     18  I  120   4 HCHAR
     22  I  128   4 HCHAR
     26  I  136   4 HCHAR
   LOOP ;

DECIMAL
: DEFCHARS ( pattern first last -- )
        1+ SWAP ?DO   DUP I CHARDEF  8 +LOOP DROP ;

: SET-COLORS ( -- )
\   charset  fg   bg
\   -------  --   --
    88 SET#  GRY  CLR COLOR
    96 SET#  YEL  CLR COLOR
   104 SET#  CYAN CLR COLOR
   112 SET#  GRN  CLR COLOR
   120 SET#  MAG  CLR COLOR
   128 SET#  RED  CLR COLOR
   136 SET#  BLU  CLR COLOR
   144 SET#  BLK  CLR COLOR ;

\ restore characters and colors
: DEFAULTS   
   8 SCREEN
   4 19 BLK CLR COLORS
   CLEAR
   CHARSET ;

: BARS
   CLEAR  BLK SCREEN
   SET-COLORS
   SQUARE 88 152 DEFCHARS
   COLOR-BARS
   BEGIN ?TERMINAL  UNTIL
   DEFAULTS
;

CR .( Done. Type BARS to run)

Go

Library: Go Graphics
package main

import "github.com/fogleman/gg"

var colors = [8]string{
    "000000", // black
    "FF0000", // red
    "00FF00", // green
    "0000FF", // blue
    "FF00FF", // magenta
    "00FFFF", // cyan
    "FFFF00", // yellow
    "FFFFFF", // white
}

func drawBars(dc *gg.Context) {
    w := float64(dc.Width() / len(colors))
    h := float64(dc.Height())
    for i := range colors {
        dc.SetHexColor(colors[i])
        dc.DrawRectangle(w*float64(i), 0, w, h)
        dc.Fill()
    }
}

func main() {
    dc := gg.NewContext(400, 400)
    drawBars(dc)
    dc.SavePNG("color_bars.png")
}
Output:
Image similar to R entry.

Haskell

Terminal-based version.

#!/usr/bin/env stack
-- stack --resolver lts-7.0 --install-ghc runghc --package vty -- -threaded

import Graphics.Vty

colorBars :: Int -> [(Int, Attr)] -> Image
colorBars h bars = horizCat $ map colorBar bars
  where colorBar (w, attr) = charFill attr ' ' w h

barWidths :: Int -> Int -> [Int]
barWidths nBars totalWidth = map barWidth [0..nBars-1]
  where fracWidth = fromIntegral totalWidth / fromIntegral nBars
        barWidth n =
          let n' = fromIntegral n :: Double
          in floor ((n' + 1) * fracWidth) - floor (n' * fracWidth)

barImage :: Int -> Int -> Image
barImage w h = colorBars h $ zip (barWidths nBars w) attrs
  where attrs = map color2attr colors
        nBars = length colors
        colors = [black, brightRed, brightGreen, brightBlue, brightMagenta, brightCyan, brightYellow, brightWhite]
        color2attr c = Attr Default Default (SetTo c)

main :: IO ()
main = do
    cfg <- standardIOConfig
    vty <- mkVty cfg
    let output = outputIface vty
    bounds <- displayBounds output
    let showBars (w,h) = do
          let img = barImage w h
              pic = picForImage img
          update vty pic
          e <- nextEvent vty
          case e of
            EvResize w' h' -> showBars (w',h')
            _ -> return ()
    showBars bounds
    shutdown vty

Graphical version using SFML.

-- Before you can install the SFML Haskell library, you need to install
-- the CSFML C library.  (For example, "brew install csfml" on OS X.)

-- This program runs in fullscreen mode.
-- Press any key or mouse button to exit.

import Control.Exception
import SFML.Graphics
import SFML.SFResource
import SFML.Window hiding (width, height)

withResource :: SFResource a => IO a -> (a -> IO b) -> IO b
withResource acquire = bracket acquire destroy

withResources :: SFResource a => IO [a] -> ([a] -> IO b) -> IO b
withResources acquire = bracket acquire (mapM_ destroy)

colors :: [Color]
colors = [black, red, green, magenta, cyan, yellow, white]

makeBar :: (Float, Float) -> (Color, Int) -> IO RectangleShape
makeBar (barWidth, height) (c, i) = do
  bar <- err $ createRectangleShape
  setPosition  bar $ Vec2f (fromIntegral i * barWidth) 0
  setSize      bar $ Vec2f barWidth height
  setFillColor bar c
  return bar

barSize :: VideoMode -> (Float, Float)
barSize (VideoMode w h _ ) = ( fromIntegral w / fromIntegral (length colors)
                             , fromIntegral h )

loop :: RenderWindow -> [RectangleShape] -> IO ()
loop wnd bars = do
  mapM_ (\x -> drawRectangle wnd x Nothing) bars
  display wnd
  evt <- waitEvent wnd
  case evt of
    Nothing -> return ()
    Just SFEvtClosed -> return ()
    Just (SFEvtKeyPressed {}) -> return ()
    Just (SFEvtMouseButtonPressed {}) -> return ()
    _ -> loop wnd bars

main :: IO ()
main = do
  vMode <- getDesktopMode
  let wStyle = [SFFullscreen]
  withResource (createRenderWindow vMode "color bars" wStyle Nothing) $
     \wnd -> withResources (mapM (makeBar $ barSize vMode) $ zip colors [0..]) $
     \bars -> loop wnd bars

Icon and Unicon

The procedure below is generalized to take a description of a test card and display it.

link graphics,printf
                     
procedure main()  # generalized colour bars 
   DrawTestCard(Simple_TestCard())
   WDone()
end   
   
procedure DrawTestCard(TC)
   size := sprintf("size=%d,%d",TC.width,TC.height)
   &window := TC.window := open(TC.id,"g","bg=black",size) | 
               stop("Unable to open window")   

   every R := TC.bands[r := 1 to *TC.bands -1] do
      every C := R.bars[c := 1 to *R.bars - 1] do {
	     Fg(R.bars[c].colour)
	     FillRectangle( C.left, R.top,
		            R.bars[c+1].left-C.left, TC.bands[r+1].top-R.top )
	     }
   return TC
end

record testcard(window,id,width,height,bands)
record band(top,bars)    
record bar(left,colour)   

procedure Simple_TestCard()  #: return structure simple testcard
   return testcard(,"Simple Test Card",width := 800,height := 600, 
		   [   band( 1, [ bar(  1, "black"),
				  bar(114, "red"),
				  bar(228, "green"),
				  bar(342, "blue"),
                                  bar(456, "magenta"),
                                  bar(570, "cyan"),
                                  bar(684, "yellow"),
                                  bar(width) ] ),
		       band(height) ])
end

The following example is a wee tiny bit more interesting.

procedure SMPTE_TestCard()  #: return structure with 480i(ish) testcard
   return testcard(,"SMPTE TV Test Card",width := 672,height := 504, 
		   [   band(  1, [ bar(  1, "#c0c0c0"),
				   bar( 95, "#c0c000"),
   	    		           bar(191, "#00c0c0"),
				   bar(288, "#00c000"),
				   bar(383, "#c000c0"),
				   bar(480, "#c00000"),
				   bar(575, "#0000c0"),
				   bar(width) ] ),
		       band(335, [ bar(  1, "#0000c0"),
				   bar( 95, "#131313"),
				   bar(191, "#c000c0"),
				   bar(288, "#131313"),
				   bar(383, "#00c0c0"),
				   bar(480, "#131313"),
				   bar(575, "#c0c0c0"),
			           bar(width) ] ),
		       band(378, [ bar(  1, "#00214c"), 
				   bar(120, "#ffffff"),
				   bar(240, "#32006a"), 
				   bar(360, "#131313"), 
				   bar(480, "#090909"), 
				   bar(512, "#131313"), 
				   bar(544, "#1d1d1d"), 
				   bar(576, "#131313"),    
				   bar(width) ] ),
			band(height) ])
end

graphics.icn provides graphics printf.icn provides sprintf

J

   load 'viewmat'
   size=: 2{.".wd'qm' NB. J6
   size=: getscreenwh_jgtk_ '' NB. J7
   'rgb'viewmat (|.size){. (>.&.(%&160)|.size)$ 20# 256#.255*#:i.8

Note: You need to pick an implementation of size based on the version of J you are using.

Java

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;

public class ColorFrame extends JFrame {
	public ColorFrame(int width, int height) {
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setSize(width, height);
		this.setVisible(true);
	}

	@Override
	public void paint(Graphics g) {
		Color[] colors = { Color.black, Color.red, Color.green, Color.blue,
				Color.pink, Color.CYAN, Color.yellow, Color.white };

		for (int i = 0; i < colors.length; i++) {
			g.setColor(colors[i]);
			g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()
					/ colors.length, this.getHeight());
		}
	}

	public static void main(String args[]) {
		new ColorFrame(200, 200);
	}
}

Julia

Works with: Julia version 0.6
using Images

colors = [colorant"black", colorant"red", colorant"green", colorant"darkblue",
          colorant"purple", colorant"blue", colorant"yellow", colorant"white"]
wcol = 60 # width of each color bar
h, w = 150, wcol * length(colors) + 1
img = Matrix{RGB{N0f8}}(h, w);
for (j, col) in zip(1:wcol:w, colors)
    img[:, j:j+wcol] = col
end
save("data/colourbars.jpg", img)

Kotlin

Translation of: Java
import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame

class ColorFrame(width: Int, height: Int): JFrame() {
    init {
        defaultCloseOperation = EXIT_ON_CLOSE
        setSize(width, height)
        isVisible = true
    }

    override fun paint(g: Graphics) {
        val colors = listOf(Color.black, Color.red,  Color.green,  Color.blue,
		            Color.pink,  Color.cyan, Color.yellow, Color.white)
        val size = colors.size
        for (i in 0 until size) {
            g.color = colors[i]
            g.fillRect(width / size * i, 0, width / size, height)
        }
    }
}

fun main(args: Array<String>) {
    ColorFrame(400, 400)
}

Editing Babbage problem

Lua

Library: nw
Library: cairo
local nw = require("nw")
local app = nw:app()
local cw, ch = 320, 240
local win = app:window(cw, ch, "Color Bars", false)
local colors = {{0,0,0}, {1,0,0}, {0,1,0}, {0,0,1}, {1,0,1}, {0,1,1}, {1,1,0}, {1,1,1}}
local unpack = unpack or table.unpack -- polyfill 5.2 vs 5.3
function win:repaint()
  local cr = win:bitmap():cairo()
  for i = 1, #colors do
    cr:rectangle((i-1)*cw/#colors, 0, cw/#colors, ch)
    cr:rgb(unpack(colors[i]))
    cr:fill()
  end 
end
win:show()
app:run()

M2000 Interpreter

Calling a module can be done by using name or call name. The later used for recursive call. Here we use it for beautify the code.

Module Checkit {
      Module Bars {
            barwidth=x.twips div 8
            barheight=y.twips
            barcolors=(0,#ff0000,#00ff00, #0000ff, #FF00FF, #00ffff, #ffff00, #ffffff)
            For i=0 to 7
                  Move i*barwidth, 0
                  \\ gradient fill. Here second color are the same as first color
                  Fill barwidth, barheight, array(barcolors, i), array(barcolors, i)
            Next i
      }
      \\ first draw on console
      Call Bars
      Declare Form1 Form
      Layer Form1 {
            window 12, 10000,8000;
            \\ now draw on Form1 layer, above console, in a window
            Call Bars
      }
      Method Form1, "Show", 1 ' open modal
      Declare Form1 Nothing
}
Checkit

Maple

with(plottools):
plots:-display([rectangle([0, 0], [.3, 2.1], color = black), rectangle([.3, 0], [.6, 2.1], color = red), rectangle([.6, 0], [.9, 2.1], color = green), rectangle([.9, 0], [1.2, 2.1], color = magenta), rectangle([1.2, 0], [1.5, 2.1], color = cyan), rectangle([1.5, 0], [1.8, 2.1], color = white), rectangle([1.8, 0], [2.1, 2.1], color = yellow)])

Mathematica / Wolfram Language

ArrayPlot[
 ConstantArray[{Black, Red, Green, Blue, Magenta, Cyan, Yellow, 
   White}, 5]]

Nim

Library: gintro
import gintro/[glib, gobject, gtk, gio, cairo]

const
  Width = 400
  Height = 300

#---------------------------------------------------------------------------------------------------

proc draw(area: DrawingArea; context: Context) =
  ## Draw the color bars.

  const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0],
                  [0.0, 255.0, 0.0], [0.0, 0.0, 255.0],
                  [255.0, 0.0, 255.0], [0.0, 255.0, 255.0],
                  [255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]

  const
    RectWidth = float(Width div Colors.len)
    RectHeight = float(Height)

  var x = 0.0
  for color in Colors:
    context.rectangle(x, 0, RectWidth, RectHeight)
    context.setSource(color)
    context.fill()
    x += RectWidth

#---------------------------------------------------------------------------------------------------

proc onDraw(area: DrawingArea; context: Context; data: pointer): bool =
  ## Callback to draw/redraw the drawing area contents.

  area.draw(context)
  result = true

#---------------------------------------------------------------------------------------------------

proc activate(app: Application) =
  ## Activate the application.

  let window = app.newApplicationWindow()
  window.setSizeRequest(Width, Height)
  window.setTitle("Color bars")

  # Create the drawing area.
  let area = newDrawingArea()
  window.add(area)

  # Connect the "draw" event to the callback to draw the spiral.
  discard area.connect("draw", ondraw, pointer(nil))

  window.showAll()

#———————————————————————————————————————————————————————————————————————————————————————————————————

let app = newApplication(Application, "Rosetta.ColorBars")
discard app.connect("activate", activate)
discard app.run()

OCaml

open Graphics

let round x =
  int_of_float (floor (x +. 0.5))

let () =
  open_graph "";
  let cols = size_x () in
  let rows = size_y () in
  let colors = [| black; red; green; blue; magenta; cyan; yellow; white |] in
  let n = Array.length colors in
  let bar_width = (float cols) /. (float n) in
  Array.iteri (fun i color ->
    let x1 = bar_width *. (float i) in
    let x2 = bar_width *. (float (succ i)) in
    set_color color;
    fill_rect (round x1) 0 (round x2) rows;
  ) colors;
  ignore (read_key ());
;;

execute with:

$ ocaml graphics.cma display_colour_bars.ml

Perl

use strict;
use warnings;
use GD;

my %colors = (
white   => [255,255,255], red    => [255,  0,  0], green => [  0,255,  0], blue  => [  0,  0,255],
magenta => [255,  0,255], yellow => [255,255,  0], cyan  => [  0,255,255], black => [  0,  0,  0]);

my $start    = 0;
my $barwidth = 160 / 8;
my $image    = GD::Image->new( 160 , 100 );

for my $rgb ( values %colors ) {
   $image->filledRectangle( $start * $barwidth , 0 , $start * $barwidth + 
	                        $barwidth - 1 , 99 , $image->colorAllocate( @$rgb ) );
   $start++ ;
}
open ( DISPLAY , ">" , "bars.png" ) or die;
binmode DISPLAY;
print DISPLAY $image->png;
close DISPLAY;

Phix

Library: Phix/pGUI
-- demo\rosetta\Colour_bars.exw
with javascript_semantics
include pGUI.e

constant colours = {CD_BLACK, CD_RED, CD_GREEN, CD_BLUE, CD_MAGENTA, CD_CYAN, CD_YELLOW, CD_WHITE}

Ihandle dlg, canvas
cdCanvas cdcanvas

function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
    integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE"),
            x = 0, lc = length(colours)
    cdCanvasActivate(cdcanvas)
    for i=1 to lc do
        integer w = floor((width-x)/(lc-i+1))
        cdCanvasSetForeground(cdcanvas, colours[i])
        cdCanvasBox(cdcanvas, x, x+w, 0, height)
        x += w
    end for
    cdCanvasFlush(cdcanvas)
    return IUP_DEFAULT
end function

IupOpen()
canvas = IupCanvas(Icallback("redraw_cb"),"RASTERSIZE=600x400") -- initial size
dlg = IupDialog(canvas,`TITLE="Colour bars"`)
IupMap(dlg)
cdcanvas = cdCreateCanvas(CD_IUP, canvas)
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if

PHP

Translation of: Perl

Will output result directly to the browser. Use it as CGI/BIN script.

<?php
$colors = array(array(  0,   0,   0),   // black
                array(255,   0,   0),   // red
                array(  0, 255,   0),   // green
                array(  0,   0, 255),   // blue
                array(255,   0, 255),   // magenta
                array(  0, 255, 255),   // cyan
                array(255, 255,   0),   // yellow
                array(255, 255, 255));  // white

define('BARWIDTH', 640 / count($colors));
define('HEIGHT',   480);

$image = imagecreate(BARWIDTH * count($colors), HEIGHT);

foreach ($colors as $position => $color) {
    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
    imagefilledrectangle($image, $position * BARWIDTH, 0,
                         $position * BARWIDTH + BARWIDTH - 1,
                         HEIGHT - 1, $color);
}

header('Content-type:image/png');
imagepng($image);
imagedestroy($image);

Alternately, with HTML output:

<?php
$colors = array(
                "000000",   // black
                "FF0000",   // red
                "00FF00",   // green
                "0000FF",   // blue
                "FF00FF",   // magenta
                "00FFFF",   // cyan
                "FFFF00",   // yellow
                "FFFFFF",   // white
                );

echo '<table style="border: 1px solid black; border-spacing: 0;"><tr>';
foreach ($colors as $color) {
    echo '<td style="background-color: #'.$color.'; height: 100px; width: 20px;"></td>';
}
echo '</tr></table>';

PicoLisp

Translation of: UNIX Shell
(call 'clear)

(let Width (in '(tput cols) (read))
   (do (in '(tput lines) (read))
      (for B (range 0 7)
         (call 'tput 'setab B)
         (space (/ Width 8)) )
      (prinl) ) )

(call 'tput 'sgr0)   # reset

Plain English

To run:
Start up.
Clear the screen.
Divide the screen width by 8 giving a bar width.
Make a bar with 0 and 0 and the bar width and the screen's bottom.
Draw the color bars using the bar.
Refresh the screen.
Wait for the escape key.
Shut down.

To divide the screen width by a number giving a width:
Put the screen's right into the width.
Divide the width by the number.

A bar is a box.

To draw a bar using a color and move it over:
Draw and fill the bar with the color.
Move the bar right the bar's width.

To draw the color bars using a bar:
Draw the bar using the black color and move it over.
Draw the bar using the red color and move it over.
Draw the bar using the green color and move it over.
Draw the bar using the blue color and move it over.
Draw the bar using the magenta color and move it over.
Draw the bar using the cyan color and move it over.
Draw the bar using the yellow color and move it over.
Draw and fill the bar using the white color.

PowerShell

[string[]]$colors = "Black"   , "DarkBlue"   , "DarkGreen" , "DarkCyan",
                    "DarkRed" , "DarkMagenta", "DarkYellow", "Gray",
                    "DarkGray", "Blue"       , "Green"     , "Cyan",
                    "Red"     , "Magenta"    , "Yellow"    , "White"

for ($i = 0; $i -lt 64; $i++)
{ 
    for ($j = 0; $j -lt $colors.Count; $j++)
    { 
        Write-Host (" " * 12) -BackgroundColor $colors[$j] -NoNewline
    }

    Write-Host
}

Processing

fullScreen();
noStroke();
color[] cs = {
  color(0),         // black
  color(255,0,0),   // red
  color(0,255,0),   // green
  color(255,0,255), // magenta
  color(0,255,255), // cyan
  color(255,255,0), // yellow
  color(255)        // white
};
for(int i=0; i<7; i++) {
  fill(cs[i]);
  rect(i*width/8,0,width/8,height);
}

Python

#!/usr/bin/env python
#vertical coloured stripes in window in Python 2.7.1

from livewires import *

horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)

for index,each in enumerate(NameColors):
	ExcStrng="set_colour(Colour."+each+")"
	exec ExcStrng
	box(index*stepik,0,(index+1)*stepik,vert,filled=1)

while keys_pressed() != ['x']: # press x key to terminate program
	pass

end_graphics()

R

Create the color palette, set margins to zero so the image will fill the display, and use image to create the graphic:

pal <- c("black", "red", "green", "blue", "magenta", "cyan", "yellow", "white")
par(mar = rep(0, 4)) 
image(matrix(1:8), col = pal, axes = FALSE)

Racket

#lang racket/gui

(define-values [W H] (get-display-size #t))

(define colors
  '("Black" "Red" "Green" "Blue" "Magenta" "Cyan" "Yellow" "White"))

(define (paint-pinstripe canvas dc)
  (send dc set-pen "black" 0 'transparent)
  (for ([x (in-range 0 W (/ W (length colors)))] [c colors])
    (send* dc (set-brush c 'solid) (draw-rectangle x 0 W H))))

(define full-frame%
  (class frame%
    (define/override (on-subwindow-char r e)
      (when (eq? 'escape (send e get-key-code))
        (send this show #f)))
    (super-new
     [label "Color bars"] [width W] [height H]
     [style '(no-caption no-resize-border hide-menu-bar no-system-menu)])
    (define c (new canvas% [parent this] [paint-callback paint-pinstripe]))
    (send this show #t)))

(void (new full-frame%))

Raku

(formerly Perl 6)

Works with: Rakudo version 2018.10
my ($x,$y) = 1280, 720;

my @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $x div 8) },
      0,   0,   0,
    255,   0,   0,
      0, 255,   0,
      0,   0, 255,
    255,   0, 255,
      0, 255, 255,
    255, 255,   0,
    255, 255, 255;

my $img = open "colorbars.ppm", :w orelse die "Can't create colorbars.ppm: $_";

$img.print: qq:to/EOH/;
    P6
    # colorbars.ppm
    $x $y
    255
    EOH

for ^$y {
    for ^@colors -> $h {
        $img.write: @colors[$h];
    }
}

$img.close;

REXX

Works with: PC REXX
Works with: Personal REXX
Works with: R4
Works with: ROO


Programming note:   because of the way the REXX interpreters   (being used for this example)   ensure screen output fidelity,   if ninety characters are displayed on a ninety-byte wide screen,   REXX apparently forces an extra blank,   causing to what appears to be a blank line after the line displayed.   Because of this,   the last color bar   (_.8)   has been shortened by one byte.

/*REXX program  displays  eight colored vertical bars  on a full screen.                */
parse  value  scrsize()  with sd sw .                 /*the screen depth and width.     */
barWidth=sw%8                                         /*calculate the bar width.        */
_.=copies('db'x, barWidth)                            /*the bar, full width.            */
_.8=left(_.,barWidth-1)                               /*the last bar width,  less one.  */
    $ = x2c('1b5b73')  ||  x2c("1b5b313b33376d")      /* the preamble,  and the header. */
hdr.1 = x2c('1b5b303b33306d')                         /*  "  color black.               */
hdr.2 = x2c('1b5b313b33316d')                         /*  "  color red.                 */
hdr.3 = x2c('1b5b313b33326d')                         /*  "  color green.               */
hdr.4 = x2c('1b5b313b33346d')                         /*  "  color blue.                */
hdr.5 = x2c('1b5b313b33356d')                         /*  "  color magenta.             */
hdr.6 = x2c('1b5b313b33366d')                         /*  "  color cyan.                */
hdr.7 = x2c('1b5b313b33336d')                         /*  "  color yellow.              */
hdr.8 = x2c('1b5b313b33376d')                         /*  "  color white.               */
 tail = x2c('1b5b751b5b303b313b33363b34303b306d')     /*  "  epilogue,  and the trailer.*/
                                                      /* [↓]  last bar width is shrunk. */
       do j=1  for 8                                  /*build the line, color by color. */
       $=$ || hdr.j || _.j                            /*append the color header + bar.  */
       end   /*j*/                                    /* [↑]  color order is the list.  */
                                                      /* [↓]  the tail is overkill.     */
$=$ || tail                                           /*append the epilogue (trailer).  */
                                                      /* [↓]  show full screen of bars. */
       do k=1  for sd                                 /*SD = screen depth (from above). */
       say $                                          /*have REXX display line of bars. */
       end   /*k*/                                    /* [↑]  Note:  SD  could be zero. */
                                                      /*stick a fork in it, we're done. */

This REXX program makes use of   scrsize   REXX program (or BIF) which is used to determine the screen size of the terminal (console).

The   SCRSIZE.REX   REXX program is included here   ──►   SCRSIZE.REX.

output   appears identical to the output for   Icon and Unicon,   Mathematica,   and   R   examples.

Ring

load "guilib.ring"

new qapp 
        {
        win1 = new qwidget() {
               setwindowtitle("drawing using qpainter")
               setwinicon(self,"C:\Ring\bin\image\browser.png")
               setgeometry(100,100,500,600)
               label1 = new qlabel(win1) {
                        setgeometry(10,10,400,400)
                        settext("")
               }
               new qpushbutton(win1) {
                   setgeometry(200,400,100,30)
                   settext("draw")
                   setclickevent("draw()")
               }
               show()
        }
        exec()
        }

func draw
     p1 = new qpicture()
          color = new qcolor() {
          setrgb(0,0,255,255)
     }
     pen = new qpen() {
           setcolor(color)
           setwidth(1)
     }
     new qpainter() {
         begin(p1)
         setpen(pen)

     //Black, Red, Green, Blue, Magenta, Cyan, Yellow, White
          
     for n = 1 to 8
         color2 = new qcolor(){
         switch n
                on 1 r=0 g=0 b=0
                on 2 r=255 g=0 b=0
                on 3 r=0 g=255 b=0
                on 4 r=0 g=0 b=255
                on 5 r=255 g=0 b=255
                on 6 r=0 g=255 b=255
                on 7 r=255 g=255 b=0
                on 8 r=255 g=255 b=255
           off
           setrgb(r,g,b,255)
           }
           mybrush = new qbrush() {setstyle(1) setcolor(color2)}
           setbrush(mybrush)
           drawrect(n*25,25,25,70)
     next

     endpaint()
     }
     label1 { setpicture(p1) show() }

Output : Colour bars

Ruby

Library: RubyGems
Library: JRubyArt

JRubyArt is a port of Processing to the ruby language

# Array of web colors black, red, green, blue, magenta, cyan, yellow, white
PALETTE = %w[#000000 #ff0000 #00ff00 #0000ff #ff00ff #00ffff #ffffff].freeze

def settings
  full_screen
end

def setup
  PALETTE.each_with_index do |col, idx|
    fill color(col)
    rect(idx * width / 8, 0, width / 8, height)
  end
end

Rust

Library: winit
Library: pixels

renders into a borderless fullscreen window on the primary display. press ESC to close

use pixels::{Pixels, SurfaceTexture}; // 0.2.0
use winit::event::*; // 0.24.0
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::{Fullscreen, WindowBuilder};

fn main() {
    let event_loop = EventLoop::new();
    let window = WindowBuilder::new()
        .with_title("Colour Bars")
        .with_decorations(false)
        .with_fullscreen(Some(Fullscreen::Borderless(None)))
        .build(&event_loop).unwrap();
    let size = window.inner_size();
    let texture = SurfaceTexture::new(size.width, size.height, &window);
    let mut image_buffer = Pixels::new(8, 1, texture).unwrap();
    let frame = image_buffer.get_frame();
    frame.copy_from_slice(&[
        0x00, 0x00, 0x00, 0xFF, // black
        0xFF, 0x00, 0x00, 0xFF, // red
        0x00, 0xFF, 0x00, 0xFF, // green
        0x00, 0x00, 0xFF, 0xFF, // blue
        0xFF, 0x00, 0xFF, 0xFF, // magenta
        0x00, 0xFF, 0xFF, 0xFF, // cyan
        0xFF, 0xFF, 0x00, 0xFF, // yellow
        0xFF, 0xFF, 0xFF, 0xFF, // white
    ]);

    image_buffer.render().unwrap();

    event_loop.run(move |ev, _, flow| {
        match ev {
            Event::WindowEvent {
                event: WindowEvent::KeyboardInput { input, .. }, ..
            } => {
                if input.virtual_keycode == Some(VirtualKeyCode::Escape) {
                    *flow = ControlFlow::Exit;
                }
            }
            Event::RedrawRequested(_) | Event::WindowEvent {
                event: WindowEvent::Focused(true), ..
            } => {
                image_buffer.render().unwrap();
            }
            _ => {}
        }
    });
}

Scala

import java.awt.Color
import scala.swing._

class ColorBars extends Component {
  override def paintComponent(g:Graphics2D)={
    val colors=List(Color.BLACK, Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN, Color.YELLOW, Color.WHITE)
    val colCount=colors.size
    val deltaX=size.width.toDouble/colCount
    for(x <- 0 until colCount){
      val startX=(deltaX*x).toInt
      val endX=(deltaX*(x+1)).toInt
      g.setColor(colors(x))
      g.fillRect(startX, 0, endX-startX, size.height)
    }
  }
}

Open window:

new MainFrame(){
  title="Color bars"
  visible=true
  preferredSize=new Dimension(640, 320)
  contents=new ColorBars()
}

Sidef

Translation of: Perl
require('GD');

var colors = Hash.new(
              white   => [255, 255, 255],
              red     => [255, 0,   0],
              green   => [0,   255, 0],
              blue    => [0,   0,   255],
              magenta => [255, 0,   255],
              yellow  => [255, 255, 0],
              cyan    => [0,   255, 255],
              black   => [0,   0,   0],
             );

var barwidth = 160/8;
var image    = %s'GD::Image'.new(160, 100);
var start    = 0;

colors.values.each { |rgb|
    var paintcolor = image.colorAllocate(rgb...);
    image.filledRectangle(start * barwidth, 0, start*barwidth + barwidth - 1, 99, paintcolor);
    start++;
};

%f'colorbars.png'.open('>:raw').print(image.png);

Tcl

Library: Tk
package require Tcl 8.5
package require Tk 8.5

wm attributes . -fullscreen 1
pack [canvas .c -highlightthick 0] -fill both -expand 1
set colors {black red green blue magenta cyan yellow white}

for {set x 0} {$x < [winfo screenwidth .c]} {incr x 8} {
    .c create rectangle $x 0 [expr {$x+7}] [winfo screenheight .c] \
            -fill [lindex $colors 0] -outline {}
    set colors [list {*}[lrange $colors 1 end] [lindex $colors 0]]
}

UNIX Shell

#!/bin/sh
clear
WIDTH=`tput cols`
HEIGHT=`tput lines`
NUMBARS=8
BARWIDTH=`expr $WIDTH / $NUMBARS`

l="1"    # Set the line counter to 1
while [ "$l" -lt $HEIGHT ]; do
  b="0"    # Bar counter
  while [ "$b" -lt $NUMBARS ]; do
    tput setab $b
    s="0"
    while [ "$s" -lt $BARWIDTH ]; do
      echo -n " "
      s=`expr $s + 1`
    done
    b=`expr $b + 1`
  done
  echo    # newline
  l=`expr $l + 1`
done

tput sgr0    # reset

Uxntal

( uxnasm color-bars.tal color-bars.rom && uxnemu color-bars.rom )

|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1
|20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1

|0100
    ( set 4 color theme
              rgb
      color0: 000 - black
      color1: f00 - red
      color2: 0f0 - green
      color3: 00f - blue )
    #0f00 .System/r DEO2
    #00f0 .System/g DEO2
    #000f .System/b DEO2

    ( store bars width )
    .Screen/width DEI2 #0004 DIV2 ,&quarter STR2
    ( set starting position )
    #0000 .Screen/y DEO2

    ( draw bars )
    #00
    &loop
        #00 OVR [ LIT2 &quarter $2 ] MUL2
        .Screen/x DEO2
        DUP #80 ORA .Screen/pixel DEO
        INC DUP #04 NEQ ?&loop
BRK
Color bars task implemented in Uxntal.
Color bars task implemented in Uxntal.

Wren

Translation of: Go
Library: DOME
import "graphics" for Canvas, Color
import "dome" for Window

class Game {
    static init() {
        Window.title = "Color bars"
        __width = 400
        __height = 400
        Canvas.resize(__width, __height)
        Window.resize(__width, __height)
        var colors = [
            Color.hex("000000"), // black
            Color.hex("FF0000"), // red
            Color.hex("00FF00"), // green
            Color.hex("0000FF"), // blue
            Color.hex("FF00FF"), // magenta
            Color.hex("00FFFF"), // cyan
            Color.hex("FFFF00"), // yellow
            Color.hex("FFFFFF")  // white
        ]
        drawBars(colors)
    }

    static drawBars(colors) {
        var w = __width / colors.count
        var h = __height
        for (i in 0...colors.count) {
            Canvas.rectfill(w*i, 0, w, h, colors[i])
        }
    }

    static update() {}

    static draw(dt) {}
}

XPL0

include c:\cxpl\codes;       \intrinsic code declarations
int W, X0, X1, Y, C;
[SetVid($13);           \320x200x8 graphics
W:= 320/8;              \width of color bar (pixels)
for C:= 0 to 8-1 do
        [X0:= W*C; X1:= X0+W-1;
        for Y:= 0 to 200-1 do
                [Move(X0, Y); Line(X1, Y, C)];
        ];
C:= ChIn(1);            \wait for keystroke
SetVid(3);              \restore normal text mode
]