Color wheel: Difference between revisions

(Added Wren)
Line 589:
{{out}}
see [https://4.bp.blogspot.com/-0swVvNDaTjE/XDlPfuGQkBI/AAAAAAAAHno/wU3eyo1BUIEtPjZMyjGXkbN425zHJlc7wCLcBGAs/s1600/colorwheel.png this image]
 
=={{header|Nim}}==
{{trans|Rust}}
{{libheader|nimPNG}}
As Rust code does, we build the color wheel as an image and for this we use we "bitmap" module from the "Bitmap" task.
 
<lang Nim>import math
import bitmap
import nimPNG
 
#---------------------------------------------------------------------------------------------------
 
func hsvToRgb(h, s, v: float): Color =
## Convert HSV values to RGB values.
 
let hp = h / 60
let c = s * v
let x = c * (1 - abs(hp mod 2 - 1))
let m = v - c
var r, g, b = 0.0
if hp <= 1:
r = c
g = x
elif hp <= 2:
r = x
g = c
elif hp <= 3:
g = c
b = x
elif hp <= 4:
g = x
b= c
elif hp <= 5:
r = x
b = c
else:
r = c
b = x
r += m
g += m
b += m
result = (r: byte(r * 255), g: byte(g * 255), b: byte(b * 255))
 
#---------------------------------------------------------------------------------------------------
 
func buildColorWheel(image: Image) =
## Build a color wheel into the image.
 
const Margin = 10
let diameter = min(image.w, image.h) - 2 * Margin
let xOffset = (image.w - diameter) div 2
let yOffset = (image.h - diameter) div 2
let radius = diameter / 2
 
for x in 0..diameter:
let rx = x.toFloat - radius
for y in 0..diameter:
let ry = y.toFloat - radius
let r = hypot(rx, ry) / radius
if r > 1: continue
let a = 180 + arctan2(ry, -rx).radToDeg()
image[x + xOffset, y + yOffset] = hsvToRgb(a, r, 1)
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
const
Side = 400
Output = "color_wheel.png"
 
let image = newImage(Side, Side)
image.buildColorWheel()
 
# Copy the pixels into a sequence of bytes.
var bytes = newSeq[byte](image.pixels.len * 3)
copymem(addr(bytes[0]), addr(image.pixels[0]), bytes.len)
 
# Write into PNG file.
let status = savePNG24(Output, bytes, image.w, image.h)
if status.isOk:
echo "Color wheel written in file ", Output
else:
echo "Error:", status.error</lang>
 
=={{header|Perl}}==
Anonymous user