以 python 像素逐像素绘制圆圈

Drawing circles in python pixel by pixel

大家好,我有一个问题。我想以 python 像素为单位画一个圆圈,但我似乎做不到。

这是我们今天在编程class中讨论的一个问题,我的老师说可以通过使用距离公式来找到window的中心和点之间的距离在圆圈的外面,然后告诉程序如果适合这种情况就填写它。

所以这不是作业,纯粹出于我自己的好奇心。我已经为此工作了几个小时,我觉得我很接近,但肯定缺少一个关键要素。

我的目标是在window的中间放一个红色圆圈,宽度和高度在300到400之间。

我说的中心点是=到(w/2,h/2),我想把每一个离它有固定距离的点都填上。

我选择 (100, 50) 作为圆上的随机点,然后使用前两个点将变量 distance = 设置为距离公式。

两个 for 循环用于迭代 window 中的每个像素。我能够在我想要我的圆圈的地方创建一个框...但我似乎无法让接近圆圈的任何东西出现

这是我的代码,我将我的函数命名为日本国旗,因为它看起来很合适:

import cImage
import math


def japanese_flag(w, h):
    newimg = EmptyImage(w, h)
    distance = int(math.sqrt((50 - h / 2) ** 2 + (100 - w / 2) ** 2))

    for col in range(w):
        for row in range(h):
            if h/2 - distance < row < (h/2 + distance) and w / 2 - distance < col < (w / 2 + distance):
                    newpixel = Pixel(255, 0, 0) # this denotes the color red
                    newimg.setPixel(col, row, newpixel)
    return newimg

def show_one_flag(func_name):
    import random
    width = random.randint(300, 400)
    height = random.randint(200, 300)
    win = ImageWin(str(func_name),width,height)
    newimg = func_name(width, height)
    newimg.draw(win)

show_one_flag(japanese_flag)

使用平方半径进行更简单的比较

SqDist = (50 - h / 2) ** 2 + (100 - w / 2) ** 2

只画圆周,比较一些公差水平

Eps = 1
...
if (Math.Abs((h/2 - row) ** 2 + (w/2 - col) ** 2 - SqDist) < Eps)
     draw pixel

绘制实心圆:

if ((h/2 - row) ** 2 + (w/2 - col) ** 2 < SqDist)
     draw pixel