Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_rnd_interweave.py
- import tkinter as tk
- from PIL import Image, ImageDraw, ImageTk
- import random
- import math
- w, h = 600, 600
- grid_x = 40
- grid_y = 40
- grid_x_pixels = 1.1 * w
- grid_y_pixels = 1.1 * h
- sep_x = grid_x_pixels / (grid_x - 1)
- sep_y = grid_y_pixels / (grid_y - 1)
- colors = []
- def get_midpoint(x1, y1, x2, y2):
- return [(x1 + x2)/2, (y1 + y2)/2]
- def get_distance(x1, y1, x2, y2):
- return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
- def brush_points(draw, x1, y1, x2, y2, brush_height, brush_sat, brush_drift, brush_tips, c):
- mp = get_midpoint(x1, y1, x2, y2)
- d = get_distance(x1, y1, x2, y2)
- angle = random.random() * 2 * math.pi
- cos_a = math.cos(angle)
- sin_a = math.sin(angle)
- for i in range(-brush_height, brush_height, brush_sat):
- fi = random.uniform(-brush_drift, brush_drift)
- se = random.uniform(-brush_drift, brush_drift)
- th = random.uniform(-brush_drift, brush_drift)
- be = random.uniform(-brush_tips, brush_tips)
- en = random.uniform(-brush_tips, brush_tips)
- # Rotate points around origin
- def rotate(px, py):
- return (px * cos_a - py * sin_a, px * sin_a + py * cos_a)
- p1 = rotate(-d/2 + be, i + fi)
- p2 = rotate(0, i + se)
- p3 = rotate(d/2 + en, i + th)
- draw.line([ (x1 + p1[0], y1 + p1[1]),
- (x1 + p2[0], y1 + p2[1]),
- (x1 + p3[0], y1 + p3[1]) ],
- fill=c, width=1)
- def generate_image():
- img = Image.new("RGB", (w, h), (0, 0, 0))
- draw = ImageDraw.Draw(img)
- colors.clear()
- start_c = random.randint(0, 360)
- for i in range(8):
- hue = (start_c + i * 15) % 360
- # Convert HSB to RGB (approximate)
- rgb = hsb_to_rgb(hue, 0.3, 1.0)
- colors.append(rgb)
- current_x = w/2.0 - grid_x_pixels/2.0
- current_y = h/2.0 - grid_y_pixels/2.0
- for i in range(grid_x):
- for j in range(grid_y):
- brush_points(draw,
- current_x, current_y,
- current_x + sep_x * random.uniform(1, 2),
- current_y + sep_y * random.uniform(1, 2),
- int(sep_x/3), 1, 7, 8,
- random.choice(colors))
- current_y += sep_y
- current_y = h/2.0 - grid_y_pixels/2.0
- current_x += sep_x
- return img
- def hsb_to_rgb(h, s, b):
- h = float(h)
- s = float(s)
- b = float(b)
- h = h % 360
- c = b * s
- x = c * (1 - abs((h / 60) % 2 - 1))
- m = b - c
- if h < 60:
- r, g, b = c, x, 0
- elif h < 120:
- r, g, b = x, c, 0
- elif h < 180:
- r, g, b = 0, c, x
- elif h < 240:
- r, g, b = 0, x, c
- elif h < 300:
- r, g, b = x, 0, c
- else:
- r, g, b = c, 0, x
- return (int((r + m) * 255), int((g + m) * 255), int((b + m) * 255))
- def redraw(event=None):
- img = generate_image()
- tk_img = ImageTk.PhotoImage(img)
- canvas.img = tk_img
- canvas.create_image(0, 0, anchor=tk.NW, image=tk_img)
- # Tkinter setup
- root = tk.Tk()
- root.title("Brush Grid")
- canvas = tk.Canvas(root, width=w, height=h)
- canvas.pack()
- root.bind("<space>", redraw)
- redraw()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment