boy*_*oyd 9 java geometry image draw
我想使用像素位置绘制一个圆圈(带有1或2个循环)(从左上角开始到右下角结束)
我用这个方法成功绘制了一个矩形:
private void drawrect(int width,int height,int x,int y) {
int top=y;
int left=x;
if(top<0){
height+=top;
top=0;
}
if(left<0){
width+=left;
left=0;
}
for (int j = 0; j <width; j++) {
for (int i = 0; i <height; i++) {
pixels[((i+top)*w)+j+left] = 0xffffff;//white color
}
}
}
Run Code Online (Sandbox Code Playgroud)
像素数组包含像素索引,后跟颜色.
pixels[index]=color;
Run Code Online (Sandbox Code Playgroud)
在此之前,我将此代码用于"图像"和"像素"数组(如果这对您有帮助)
img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
Run Code Online (Sandbox Code Playgroud)
但是,如何只绘制此图像中的白色像素并忽略其他像素?
小智 6
下面是用像素绘制圆的代码:它使用公式xend = x + r cos(角度)和yend = y + r sin(角度).
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <math.h>
void DrawCircle(int x, int y, int r, int color)
{
static const double PI = 3.1415926535;
double i, angle, x1, y1;
for(i = 0; i < 360; i += 0.1)
{
angle = i;
x1 = r * cos(angle * PI / 180);
y1 = r * sin(angle * PI / 180);
putpixel(x + x1, y + y1, color);
}
}
Run Code Online (Sandbox Code Playgroud)
参考:http://www.softwareandfinance.com/Turbo_C/DrawCircle.html
您可以计算两个像素之间的最小角度并改进 Kathir 解决方案
...
void DrawCircle(int x, int y, int r, int color)
{
static const double PI = 3.1415926535;
double x1, y1;
// calculates the minimun angle between two pixels in a diagonal.
// you can multiply minAngle by a security factor like 0.9 just to be sure you wont have empty pixels in the circle
double minAngle = acos(1 - 1/r);
for(double angle = 0; angle <= 360; angle += minAngle)
{
x1 = r * cos(angle);
y1 = r * sin(angle);
putpixel(x + x1, y + y1, color);
}
}
Run Code Online (Sandbox Code Playgroud)