Joa*_*les 2 android imageview onclicklistener
我需要将图像(ImageViewer)划分为块并为它们分配onClick事件监听器.为了划分图像,我使用下一个代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是只有这个函数我得到一个Bitmaps数组,它们不接受OnClickListener.我所做的是用块重建图像,并能够放大选定的块.
任何的想法?
提前致谢.
如果是单个图像不能分割成多个图像,您可以在图像视图中添加一个触摸处理程序并检查x/y坐标
例如在你的触摸处理程序中
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;
}
Run Code Online (Sandbox Code Playgroud)
你也可以将int x和y更改为float 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);
Run Code Online (Sandbox Code Playgroud)
其中cellTouched()是你处理触摸的方法...(这里你也可以使用float)
| 归档时间: |
|
| 查看次数: |
1387 次 |
| 最近记录: |