color wheel
color theory
graphic design
programming
color palette

Function for creating color wheels

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

A color wheel function maps angle and distance from center to hue and saturation. This is useful in design tools, educational apps, and color-picker interfaces. A reliable implementation should produce smooth hue transitions, correct white center behavior, and predictable output image dimensions.

Color Wheel Mapping Basics

A standard HSV wheel works like this:

  • Angle controls hue.
  • Radius controls saturation.
  • Value is kept at one for bright colors.

Pixels outside the circle are often set to transparent or white depending on your output format.

python
1import colorsys
2import math
3from PIL import Image
4
5
6def create_color_wheel(size: int = 400) -> Image.Image:
7    img = Image.new("RGB", (size, size), (255, 255, 255))
8    cx = cy = size / 2
9    max_r = size / 2
10
11    for y in range(size):
12        for x in range(size):
13            dx = x - cx
14            dy = y - cy
15            r = math.sqrt(dx * dx + dy * dy)
16            if r <= max_r:
17                hue = (math.atan2(dy, dx) / (2 * math.pi)) % 1.0
18                sat = r / max_r
19                val = 1.0
20                rr, gg, bb = colorsys.hsv_to_rgb(hue, sat, val)
21                img.putpixel((x, y), (int(rr * 255), int(gg * 255), int(bb * 255)))
22    return img
23
24
25if __name__ == "__main__":
26    wheel = create_color_wheel(300)
27    wheel.save("color_wheel.png")

This script is runnable and generates a PNG wheel.

Adding an Indicator for Selected Color

Many applications need an indicator ring or marker showing a selected angle and radius. Keep selection logic separate from generation so your wheel image can be cached.

python
1from PIL import ImageDraw
2
3
4def draw_selector(img: Image.Image, angle_deg: float, sat: float):
5    size = img.size[0]
6    cx = cy = size / 2
7    max_r = size / 2
8
9    r = max_r * max(0.0, min(1.0, sat))
10    angle = math.radians(angle_deg)
11    x = cx + math.cos(angle) * r
12    y = cy + math.sin(angle) * r
13
14    draw = ImageDraw.Draw(img)
15    draw.ellipse((x - 5, y - 5, x + 5, y + 5), outline=(0, 0, 0), width=2)

This makes user interaction easier in desktop or mobile picker tools.

Performance and Quality Improvements

Pixel-by-pixel loops are fine for small sizes, but larger wheels may need optimization. Practical improvements include:

  • Generate once and cache the image.
  • Use NumPy arrays for vectorized math.
  • Render at higher resolution and downsample for antialiasing.

If you need alpha outside the wheel, switch image mode to RGBA and set transparent pixels explicitly.

python
img = Image.new("RGBA", (size, size), (255, 255, 255, 0))

This is useful when overlaying the wheel in custom UI layouts.

Validation Strategy

Quick validations improve confidence:

  • Center pixel should be near white.
  • Outer edge should be saturated colors.
  • Opposite angles should differ in hue.

Automate these checks with simple pixel assertions in tests.

python
wheel = create_color_wheel(200)
center = wheel.getpixel((100, 100))
assert center[0] > 200 and center[1] > 200 and center[2] > 200

Building a Reusable API

A good color wheel function should expose parameters for size, brightness, and output mode so it can be reused across different products. Keep defaults sensible and avoid hardcoded values buried in loop logic.

python
1def create_color_wheel_configurable(size=400, value=1.0, mode="RGB"):
2    img = create_color_wheel(size)
3    if mode == "RGB":
4        return img
5    return img.convert(mode)
6
7img = create_color_wheel_configurable(256)
8img.save("wheel_256.png")

This keeps call sites simple and avoids repeated image post-processing code.

Sampling Colors from the Wheel

Color pickers often need reverse mapping from pointer location to HSV and RGB values. Reuse the same geometry formulas used during rendering.

python
1def sample_hsv(size: int, x: float, y: float):
2    cx = cy = size / 2
3    dx = x - cx
4    dy = y - cy
5    r = math.sqrt(dx * dx + dy * dy)
6    max_r = size / 2
7    sat = min(1.0, r / max_r)
8    hue = (math.atan2(dy, dx) / (2 * math.pi)) % 1.0
9    return hue, sat, 1.0
10
11print(sample_hsv(300, 150, 20))

Using one shared mapping function for both drawing and selection avoids visual mismatch bugs.

Common Pitfalls

  • Mixing up radians and degrees during angle calculations.
  • Forgetting to clamp saturation to valid range.
  • Generating wheel every frame in UI code and causing lag.
  • Using inconsistent coordinate origins across drawing functions.
  • Ignoring alpha handling when compositing on non-white backgrounds.

Summary

  • A color wheel maps angle to hue and radius to saturation.
  • HSV conversion provides a simple and effective implementation.
  • Keep generation and selection marker logic separate.
  • Cache or vectorize for better performance on larger images.
  • Add pixel-level checks to verify correctness.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.