【问题标题】:Android Draw Circle Pixel by PixelAndroid 逐像素绘制圆
【发布时间】:2014-03-21 17:54:52
【问题描述】:

我正在尝试使用以下代码在我的位图上逐个像素地画一个圆圈:

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);
        }
    }

}

但是有一个问题,这不是画圆..它看起来像一个三角形..

有人可以帮我吗?

提前非常感谢;)

【问题讨论】:

  • 您是否有理由这样做而不是使用Canvas?
  • 是的,我需要检查 j、k 处的每个像素以查看颜色。如果下面的像素是黑色的,我只会画一个黄色的像素
  • @Deev 我编辑了这个问题,向你展示我需要这样做......因为我需要检查像素的颜色
  • 看看 ^ 运算符在 java 中的含义
  • 顺便说一句,您正在做的事情可能很糟糕。想法,您很可能应该使用 porter duff xfer 模式

标签: android view draw pixel geometry


【解决方案1】:

我认为你需要使用 sin/cos 公式来绘制圆圈,以下代码是用 C++ 编写的,但它可以很容易地转换为 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);
      }
}

【讨论】:

  • 感谢您的回答,但我使用 Math.pow 而不是 ^ 运算符并得到了解决
【解决方案2】:

您的错误是 ^ 的错误使用,它不是幂运算符

关于我在评论中提到的 xfer 模式,请参阅此自定义视图:

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);
    }
}

【讨论】:

  • 嘿psking 我今天测试了这段代码,并注意到使用paint.setXfermode(mode) 或不使用该行没有区别......顺便说一下,AvoidXfermode 已被弃用......可以你测试一下,告诉我它是否对你有用?非常感谢
  • 它使用 Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);对于画布:)
  • 嗯,我的代码确实有效(不过我在emu上测试过),如果canvas没有alpha缓冲区,它就无法工作,你可以尝试在onDraw中调用canvas.saveLayer和canvas.restore
  • 对我来说,它使用配置为 ARGB_8888 的位图上的特定绘图 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多