问题
I am trying to draw a circle on my bitmap, pixel by pixel, using this code:
for(int j = ((int)x - 20); j < ((int)x + 20); j++){
for(int k = ((int)y - 20); k < ((int)y + 20); k++){
int colorX = bitmap.getPixel((int)j, (int)k);
if(Color.red(colorX) == 0 && Color.green(colorX) == 0 && Color.blue(colorX) == 0){
if(Math.sqrt(((j - (( int ) x )) ^ 2 ) + ((k - (( int ) y )) ^ 2) ) <= 20)
bitmap.setPixel(j, k, Color.YELLOW);
}
}
}
But there is a problem, this is not drawing a circle.. it looks like a triangle..
Can someone help me?
Thanks alot in advance ;)
回答1:
your mistake is a wrong use of ^ , its not a power operator
regarding xfer modes i mentioned in the comment, see this custom view:
class V extends View {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Xfermode mode = new AvoidXfermode(Color.BLACK, 0, AvoidXfermode.Mode.TARGET);
public V(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
int w = getWidth();
float h = getHeight() / 3f;
paint.setXfermode(null);
paint.setColor(Color.RED);
canvas.drawRect(0, 0, w, h, paint);
paint.setColor(Color.BLACK);
canvas.drawRect(0, h, w, 2*h, paint);
paint.setColor(Color.GREEN);
canvas.drawRect(0, 2*h, w, 3*h, paint);
// draw the circle: it draws only in the middle black strip
paint.setColor(Color.WHITE);
paint.setXfermode(mode);
canvas.drawCircle(w/2, 1.5f * h, h, paint);
}
}
回答2:
I think you need to use sin/cos formula to draw circle, Following code is written in C++ but It can easily convert to Java/Android.
#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);
}
}
来源:https://stackoverflow.com/questions/22566091/android-draw-circle-pixel-by-pixel