2013-04-22 76 views
2

我需要将图像(ImageViewer)分成块,并为它们分配onClick事件侦听器。对于划分的形象,我用下面的代码:Android:如何将ImageView分成块并将它们分配给ClickClickListener

private void splitImage(ImageView image, int rows, int cols) { 

    //For height and width of the small image chunks 
    int chunkHeight,chunkWidth; 

    //To store all the small image chunks in bitmap format in this list 
    ArrayList<Bitmap> chunkedImages = new ArrayList<Bitmap>(rows * cols); 

    //Getting the scaled bitmap of the source image 
    BitmapDrawable drawable = (BitmapDrawable) image.getDrawable(); 
    Bitmap bitmap = drawable.getBitmap(); 
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true); 

    chunkHeight = bitmap.getHeight()/rows; 
    chunkWidth = bitmap.getWidth()/cols; 

    //xCoord and yCoord are the pixel positions of the image chunks 
    int yCoord = 0; 
    for(int x=0; x<rows; x++){ 
     int xCoord = 0; 
     for(int y=0; y<cols; y++){ 
      chunkedImages.add(Bitmap.createBitmap(scaledBitmap, xCoord, yCoord, chunkWidth, chunkHeight)); 
      xCoord += chunkWidth; 
     } 
     yCoord += chunkHeight; 
    }  
} 

但有了这个功能只有我得到位图的数组,他们不接受OnClickListener。我所做的是用大块重建图像,并能够放大所选块。

有什么想法?

在此先感谢。

+0

怎么样设置ImageView的地方你想要显示块到OnTouchListener并从触摸获取x,y坐标?这应该是可能的.... – Opiatefuchs 2013-04-22 11:18:16

回答

5

如果它是不能被分裂成复式图像的单个图像,你可以在Touch handler到添加到图像查看和检查X/Y COORDS

例如在你的触摸处理

boolean onTouch(View v, MotionEvent ev) { 
    if (ev.getAction() == MotionEvent.ACTION_DOWN) { 
     if (ev.getPointerCount() > 0) { 
      int w = v.getWidth(); 
      int h = v.getHeight(); 
      float eX = ev.getX(0); 
      float eY = ev.getY(0); 
      int x = (int) (eX/w * 100); 
      int y = (int) (eY/h * 100); 
      // x and y would be % of the image. 
      // so you can say cell 1 is x < 25, y < 25 for a 4x4 grid 

      // TODO add a loop or something to use x and y to detect the touched segment 
     } 
    } 
    return true; 
} 

你也可以改变int x和y来使浮动x和y更加精确。对于TODO

示例代码

//somewhere in your code.. 
int ROWS = 5; 
int COLS = 5; 

// in the place of the TODO... 
int rowWidht = 100/ROWS; 
int colWidht = 100/COLS; 

int touchedRow = x/rowWidth; // should work, not tested! 
int touchedcol = y/colWidth; // should work, not tested! 

cellTouched(touchedRow, touchedCol); 

其中cellTouched()是你的方法,你可以操作触摸... (在这里你也可以使用float)

0

您可以使用网格视图来制作图像的块并在其上设置onClickListener。

0

你真的需要分割图像吗?我只是将OnTouchListener设置为整个图像。从里面,你可以得到触摸事件的坐标。然后你做一些数学计算,你应该能够知道要放大的图像的哪一部分。

相关问题