Draw a pixel

From Rosetta Code
Revision as of 00:53, 7 February 2019 by Soxfox42 (talk | contribs) (Add SmileBASIC implementation)
Task
Draw a pixel
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Create a window and draw a pixel in it, subject to the following:

  1.  the window is 320 x 240
  2.  the color of the pixel must be red (255,0,0)
  3.  the position of the pixel is x = 100, y = 100


BASIC256

It seems that the program should be this. And the BASIC256 tutorial programs work on my ubuntu system. This program neither draws the pixel nor resizes the window. Can't see anything when I plot many spots. Oh well. I've tried the rgb(255,0,0) function as well as the fastgraphics/refresh statements. <lang BASIC256> rem http://rosettacode.org/wiki/Draw_a_pixel

graphsize 320, 240 color red plot 100, 100 </lang>

C

Requires the WinBGIm library. <lang C>

  1. include<graphics.h>

int main() { initwindow(320,240,"Red Pixel");

putpixel(100,100,RED);

getch();

return 0; } </lang>

Commodore BASIC

Example 1: Commodore 64

There are no graphics commands in Commodore 64 BASIC. High resolution (hires) graphics are programmed by directly manipulating the hardware registers and memory.

The Commodore 64 hires bitmap is 320×200, subdivided into 8×8 cells starting at the top left and moving right. Each cell is addressed top to bottom by 8 bytes. Each byte controls a horizontal row of 8 bits. This requires calculation on the programmer's part to translate X,Y coordinates into a specific memory address/value combination (lines 30 through 60).

<lang gwbasic>10 REM PLOT A RED PIXEL AT 100,100 20 REM INITIALIZE BITMAP MODE 21 POKE 53280,0:PRINT CHR$(147);"CLEARING BITMAP... PLEASE WAIT..." 22 BASE=8192:FOR I=BASE TO BASE+7999:POKE I,0:NEXT 23 PRINT CHR$(147); 24 POKE 53272,PEEK(53272) OR 8:REM SET BITMAP MEMORY AT 8192 ($2000) 25 POKE 53265,PEEK(53265) OR 32:REM ENTER BITMAP MODE 26 REM PLOT PIXEL 30 X=100:Y=100 40 MEM=BASE+INT(Y/8)*320+INT(X/8)*8+(Y AND 7) 50 PX=7-(X AND 7) 60 POKE MEM,PEEK(MEM) OR 2^PX 65 REM WAIT FOR KEYPRESS 70 GET K$:IF K$="" THEN 70 75 REM CLEAR PIXEL, RETURN TO TEXT MODE 80 POKE MEM,0:POKE 53265,PEEK(53265) AND 223:POKE 53272,PEEK(53272) AND 247 90 POKE 53280,14:POKE 53281,6:POKE 646,14:END</lang>

Example 2: Commodore Plus 4 and 128 <lang gwbasic>10 COLOR 0,1:COLOR 1,3: REM SET BORDER TO BLACK AND PIXEL COLOR TO RED 15 GRAPHIC 1,1 : REM ENTER BITMAP GRAPHICS MODE AND CLEAR SCREEN 20 DRAW 1,100,100 : REM PLOT PIXEL AT 100,100 30 GET K$:IF K$="" THEN 30 40 GRAPHIC 0,1 : REM RETURN TO TEXT MODE</lang>

FreeBASIC

<lang freebasic>' version 27-06-2018 ' compile with: fbc -s console ' or: fbc -s gui

Screen 13 ' Screen 18: 320x200, 8bit colordepth 'ScreenRes 320, 200, 24 ' Screenres: 320x200, 24bit colordepth

If ScreenPtr = 0 Then

   Print "Error setting video mode!"
   End

End If

Dim As UInteger depth, x = 100, y = 100

' what is color depth ScreenInfo ,,depth

If depth = 8 Then

   PSet(x, y), 40   ' palette, index 40 = RGB(255, 0, 0)

Else

   PSet(x, y), RGB(255, 0, 0) ' red

End If

' empty keyboard buffer While Inkey <> "" : Wend WindowTitle IIf(depth = 8, "Palette","True Color") + ", hit any key to end program" Sleep End</lang>

Go

<lang go>package main

import (

   "fmt"
   "image"
   "image/color"
   "image/draw"

)

func main() {

   rect := image.Rect(0, 0, 320, 240)
   img := image.NewRGBA(rect)
   // Use green background, say.
   green := color.RGBA{0, 255, 0, 255}
   draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)
   // Set color of pixel at (100, 100) to red
   red := color.RGBA{255, 0, 0, 255}
   img.Set(100, 100, red)
   // Check it worked.
   cmap := map[color.Color]string{green: "green", red: "red"}
   c1 := img.At(0, 0)
   c2 := img.At(100, 100)
   fmt.Println("The color of the pixel at (  0,   0) is", cmap[c1], "\b.")
   fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.")

}</lang>

Output:
The color of the pixel at (  0,   0) is green.
The color of the pixel at (100, 100) is red.

IS-BASIC

<lang IS-BASIC>100 SET VIDEO X 40:SET VIDEO Y 26:SET VIDEO MODE 5:SET VIDEO COLOR 0 110 OPEN #101:"video:" 120 DISPLAY #101:AT 1 FROM 1 TO 26 130 SET PALETTE BLACK,RED 140 PLOT 100,100</lang>

Julia

<lang julia>using Gtk, Graphics

const can = @GtkCanvas() const win = GtkWindow(can, "Draw a Pixel", 320, 240)

draw(can) do widget

   ctx = getgc(can)
   set_source_rgb(ctx, 255, 0, 0)
   move_to(ctx, 100, 100)
   line_to(ctx, 101,100)
   stroke(ctx)

end

show(can) const cond = Condition() endit(w) = notify(cond) signal_connect(endit, win, :destroy) wait(cond) </lang>


Kotlin

This task seems very similar to the Bitmap task and so therefore is the code to accomplish it. <lang scala>// Version 1.2.41

import java.awt.Color import java.awt.Graphics import java.awt.image.BufferedImage

class BasicBitmapStorage(width: Int, height: Int) {

   val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
   fun fill(c: Color) {
       val g = image.graphics
       g.color = c
       g.fillRect(0, 0, image.width, image.height)
   }
   fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
   fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))

}

fun main(args: Array<String>) {

   val bbs = BasicBitmapStorage(320, 240)
   with (bbs) {
       fill(Color.white) // say
       setPixel(100, 100, Color.red)
       // check it worked
       val c = getPixel(100, 100)
       print("The color of the pixel at (100, 100) is ")
       println(if (c == Color.red) "red" else "white")
   }

}</lang>

Output:
The color of the pixel at (100, 100) is red

M2000 Interpreter

Version 2

M2000 Console used for text and graphics too. So for this version we plot a pixel in console and in a form (a window above console). Form is open as modal, but console is something different, so we can show or hide it.

All forms are above console (for any kind, modal or not modal form), and we can hide console using Title statement. So in this example we hide/show console (behind form window) by clicking the form. In any state of showing console, when we close form and Interpreter need to input from console (like in prompt state), console state get visible.

There is also a PSet statement for pixel drawing (from 9.5 version). Just replace the module call to PlotPixel with Pset.

<lang M2000 Interpreter>


Module CheckIt {

     Module PlotPixel (a as single, b as single) {
           Move a*TwipsX, b*TwipsX
           Draw TwipsX, TwipsY
     }
     Cls 5,0  \\ clear console with Magenta (5) and set split  screen from 0 (no split screen)
     Pen #55FF77 {
           PlotPixel 1000, 200
     }
     Wait 1000
     Title "", 1
     Declare DrawPixelForm Form
     With DrawPixelForm, "Title", "Draw a Pixel at 100,100"
     Layer DrawPixelForm {
           \\ 12 for 12pt fonts
           \\ use ; to center window
           Window 12, 320*twipsx, 240*twipsy;
           Cls #333333
           Pen Color(255,0,0) {
                 PlotPixel 100, 100
           }
     }
     \\ code to show/hide console clicking form
     \\ console shown behind form
     k=0
     Function DrawPixelForm.Click {
           Title "Rosetta Code Example", abs(k)
           if k then show
           k~
     }
     Method DrawPixelForm, "Show", 1
     Declare DrawPixelForm Nothing

} CheckIt </lang> OutPut

Lua

The luasdl2 library is required.

<lang lua>local SDL = require "SDL"

local ret = SDL.init { SDL.flags.Video } local window = SDL.createWindow { title = "Pixel", height = 320, width = 240 }

local renderer = SDL.createRenderer(window, 0, 0)

renderer:clear() renderer:setDrawColor(0xFF0000) renderer:drawPoint({x = 100,y = 100}) renderer:present()

SDL.delay(5000) </lang>

Oberon

With basic module XYplane, the size of the drawing plane cannot be set. Tested with OBNC.

<lang Oberon>MODULE pixel;

IMPORT XYplane;

BEGIN XYplane.Open; XYplane.Dot(100, 100, XYplane.draw); REPEAT UNTIL XYplane.Key() = "q" END pixel. </lang>

Objeck

Library: SDL2

<lang objeck>use Game.SDL2; use Game.Framework;

class DrawPixel {

 @framework : GameFramework;
         
 function : Main(args : String[]) ~ Nil {
   DrawPixel->New()->Run();
 }
 New() {
   @framework := GameFramework->New(320, 240, "RGB");
   @framework->SetClearColor(Color->New(0, 0, 0));
 }
 method : Run() ~ Nil {
   if(@framework->IsOk()) {
     e := @framework->GetEvent();
     
     quit := false;
     while(<>quit) {
       @framework->FrameStart();
       @framework->Clear();
       while(e->Poll() <> 0) {
         if(e->GetType() = EventType->SDL_QUIT) {
           quit := true;
         };
       };
       
       @framework->GetRenderer()->SetDrawColor(255, 0, 0, 255);
       @framework->GetRenderer()->DrawPoint(100, 100);  
       @framework->Show();
       @framework->FrameEnd();
     };
   }
   else {
     "--- Error Initializing Game Environment ---"->ErrorLine();
     return;
   };
   leaving {
     @framework->Quit();
   };
 }

} </lang>

Perl

Library: Gtk3

<lang perl>use Gtk3 '-init';

my $window = Gtk3::Window->new(); $window->set_default_size(320, 240); $window->set_border_width(10); $window->set_title("Draw a Pixel"); $window->set_app_paintable(TRUE);

my $da = Gtk3::DrawingArea->new(); $da->signal_connect('draw' => \&draw_in_drawingarea); $window->add($da); $window->show_all();

Gtk3->main;

sub draw_in_drawingarea {

 my ($widget, $cr, $data) = @_;
 $cr->set_source_rgb(1, 0, 0);
 $cr->set_line_width(1);
 $cr->rectangle( 100, 100, 1, 1);
 $cr->stroke;

}</lang>

Perl 6

Works with: Rakudo version 2018.05

Really? Draw a single pixel? Sigh.

<lang perl6>use GTK::Simple; use GTK::Simple::DrawingArea; use Cairo;

my $app = GTK::Simple::App.new(:title('Draw a Pixel')); my $da = GTK::Simple::DrawingArea.new; gtk_simple_use_cairo;

$app.set-content( $da ); $app.border-width = 5; $da.size-request(320,240);

sub rect-do( $d, $ctx ) {

   given $ctx {
       .rgb(1, 0, 0);
       .rectangle(100, 100, 1, 1);
       .fill;
   }

}

my $ctx = $da.add-draw-handler( &rect-do ); $app.run;</lang>

Phix

<lang Phix>include pGUI.e

cdCanvas cdcanvas

function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)

   cdCanvasActivate(cdcanvas)
   cdCanvasPixel(cdcanvas, 100, 100, CD_RED) 
   cdCanvasFlush(cdcanvas)
   return IUP_DEFAULT

end function

function map_cb(Ihandle ih)

   cdcanvas = cdCreateCanvas(CD_IUP, ih)
   return IUP_DEFAULT

end function

procedure main()

   IupOpen()
   Ihandle canvas = IupCanvas(NULL)
   IupSetAttribute(canvas, "RASTERSIZE", "320x240")
   IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
   Ihandle dlg = IupDialog(canvas)
   IupSetAttribute(dlg, "TITLE", "Draw a pixel")
   IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
   IupCloseOnEscape(dlg) 
   IupShow(dlg)
   IupMainLoop()
   IupClose()

end procedure

main()</lang>

PureBasic

<lang PureBasic>

 If OpenWindow(0, 0, 0, 320, 240, "Rosetta Code Draw A Pixel in PureBasic")
   If CreateImage(0, 320, 240) And StartDrawing(ImageOutput(0))
         Plot(100, 100,RGB(255,0,0))
     StopDrawing() 
     ImageGadget(0, 0, 0, 320, 240, ImageID(0))
   EndIf
   Repeat
     Event = WaitWindowEvent()
   Until Event = #PB_Event_CloseWindow
 EndIf

</lang>

Python

Works with: Python version 2.7.14
Library: PIL

<lang Python>from PIL import Image

img = Image.new('RGB', (320, 240)) pixels = img.load() pixels[100,100] = (255,0,0) img.show() </lang>

QBASIC

<lang qbasic>' http://rosettacode.org/wiki/Draw_a_pixel ' This program can run in QBASIC, QuickBASIC, gw-BASIC (adding line numbers) and VB-DOS SCREEN 1 COLOR , 0 PSET (100, 100), 2 END </lang>

Racket

<lang racket>#lang racket (require racket/draw) (let ((b (make-object bitmap% 320 240)))

 (send b set-argb-pixels 100 100 1 1 (bytes 255 0 0 255))
 b)</lang>

Ring

<lang ring># Project  : Draw a pixel

load "guilib.ring"

new qapp {

      win1 = new qwidget() {
                 setwindowtitle("Drawing Pixels")
                 setgeometry(100,100,320,240)
                 label1 = new qlabel(win1) {
                             setgeometry(10,10,300,200)
                             settext("")
                 }
                 new qpushbutton(win1) {
                        setgeometry(200,200,100,30)
                        settext("draw")
                        setclickevent("draw()")
                 }
                 show()
      }
      exec()

}

func draw()

       p1 = new qpicture()
       color = new qcolor() {
                  setrgb(255,0,0,255)
                 }
       pen = new qpen() {
                 setcolor(color)
                 setwidth(5)
                 }
       new qpainter() {
              begin(p1)
              setpen(pen)
              drawpoint(100,100)
              endpaint()
              }
              label1 { setpicture(p1) show() }</lang>

Output image: Draw a pixel

Rust

Library: piston_window
Library: image
Output Image:

RustOut


<lang rust>extern crate piston_window; extern crate image;

use piston_window::*;

fn main() {

   let (width, height) = (320, 240);
   
   let mut window: PistonWindow =
       WindowSettings::new("Red Pixel", [width, height])
       .exit_on_esc(true).build().unwrap();
   // Since we cant manipulate pixels directly, we need to manipulate the pixels on a canvas.
   // Only issue is that sub-pixels exist (which is probably why the red pixel looks like a smear on the output image)
   let mut canvas = image::ImageBuffer::new(width, height);
   canvas.put_pixel(100, 100, image::Rgba([0xff, 0, 0, 0xff]));
   // Transform into a texture so piston can use it.
   let texture: G2dTexture = Texture::from_image(
       &mut window.factory,
       &canvas,
       &TextureSettings::new()
   ).unwrap();
   // The window event loop.
   while let Some(event) = window.next() {
       window.draw_2d(&event, |context, graphics| {
           clear([1.0; 4], graphics);
           image(&texture,
           context.transform,
           graphics);
       });
   }

} </lang>

Scala

Scala idiom

A more Scalesque version could be with the use of its idiom:

Output:

Best experienced in your browser with Scastie (remote JVM). <lang scala>import java.awt.image.BufferedImage import java.awt.Color import scala.language.reflectiveCalls

object RgbBitmap extends App {

 class RgbBitmap(val dim: (Int, Int)) {
   def width = dim._1
   def height = dim._2
   private val image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
   def apply(x: Int, y: Int) = new Color(image.getRGB(x, y))
   def update(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB)
   def fill(c: Color) = {
     val g = image.getGraphics
     g.setColor(c)
     g.fillRect(0, 0, width, height)
   }
 }
 object RgbBitmap {
   def apply(width: Int, height: Int) = new RgbBitmap(width, height)
 }
 /** Even Javanese style testing is still possible.
   */
 private val img0 = new RgbBitmap(50, 60) { // Wrappers to enable adhoc Javanese style
   def getPixel(x: Int, y: Int) = this(x, y)
   def setPixel(x: Int, y: Int, c: Color) = this(x, y) = c
 }
 img0.fill(Color.CYAN)
 img0.setPixel(5, 6, Color.BLUE)
 // Testing in Java style
 assert(img0.getPixel(0, 1) == Color.CYAN)
 assert(img0.getPixel(5, 6) == Color.BLUE)
 assert(img0.width == 50)
 assert(img0.height == 60)
 println("Tests successfully completed with no errors found.")

}</lang>

SmileBASIC

I almost said that the 320x240 requirement was not going to happen. Then I realised the 3DS bottom screen is exactly 320x240. <lang smilebasic>DISPLAY 1 GPSET 100, 100, RGB(255, 0, 0) WAIT 60</lang>

VBA

Word <lang vb>Sub draw()

   Dim sh As Shape, sl As Shape
   Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)
   Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)
   sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)

End Sub</lang>