Android使用位图查找x和y位置

时间:2014-08-12 23:04:57

标签: android image bitmap getpixel

我在弄清楚错误时遇到了一些麻烦。我试图根据其中包含的颜色找到位图的x和y位置。在这种情况下,我使用蓝色作为标记,已经添加到背景中并找到它所处的位置。听到我的代码:

`

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.util.Log;


public class drawing extends ImageView {

    Canvas mainCanvas;
    Drawable background;

public drawing(Context context){
        super(context);
 }
    @Override
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);

        //creating a bitmap for editing with static image
        BitmapFactory.Options mNoScale = new BitmapFactory.Options();
        mNoScale.inScaled = false;
        Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.bmvfinal1, mNoScale);

        //calling method to find the text area and sending the bit map 
        findTextAreas(background);



    }

    private void findTextAreas(Bitmap myBitmap) {
         //setting the array for getting pixel values
         int[] colorArray;
        colorArray = new int[myBitmap.getHeight() * myBitmap.getWidth()];
        //getting the pixels from the bitmap
        myBitmap.getPixels(colorArray,0,myBitmap.getWidth(),0,0,myBitmap.getWidth(),myBitmap.getHeight() );


        //looping through the array of pixels
        for(int i = 0;i<colorArray.length;i++){
           int test =  colorArray[i];
        String testing = String.format("#%06X", (0xFFFFFF & test));
           //getting the values of the colors of each position in the array
       int blue = Color.blue(test);
       int red = Color.red(test);
       int green = Color.green(test);
         //finding the small dot that I added to the black and white page
               if (blue>200 && red<100 && green<10){
          Log.d("sdf","working!!!!!!!!!!!!!!!! "+ Integer.toString(i) );


               //trying to find the x and the y position with these calculation 
           int y = i/myBitmap.getWidth();
           int x = i-((y-1)*myBitmap.getWidth());
           Log.d("sdf","x: "+ Integer.toString(x)+ "y: " + Integer.toString(y) );
 }
}
        Log.d("sdf","done checking");
}

}

`

代码似乎工作正常,直到我尝试找到x和y值。似乎这些是正确的方程,但结果是正确位置的y,但x是大的。任何有关代码的帮助或评论将不胜感激。

这是我正在使用的图片: Link to image example

1 个答案:

答案 0 :(得分:1)

尝试更改

int x = i-((y-1)*myBitmap.getWidth());

int x = i%myBitmap.getWidth();

%是模运算符,它以整数除法得到余数。通过取位图宽度的模数,我们可以得到列号。例如,假设我们的位图是4x4像素:

+-------------+
| 0  1  2  3  |
+-------------+
| 4  5  6  7  |
+-------------+
| 8  9  10 11 |
+-------------+
| 12 13 14 15 |
+-------------+

现在,如果我们进行以下计算,请说我们的像素是数字5:

5 mod 4

结果为1,因为5/4的整数除法的余数为1。现在,将其与表格进行比较,您可以看到列号也是1。

希望这有帮助!