我正在制作滑动拼图类游戏 ( http://en.wikipedia.org/wiki/Sliding_puzzle )。我希望用户能够选择图像,然后显示该图像。
但是,在此之前,我需要将他们选择的图像分成 9 个不同的方 block ,这些方 block 构成了原始图像。
关于如何在没有 Canvas 的情况下执行此操作的任何想法?或者我应该改用 Canvas 。
谢谢:)
最佳答案
您可以使用位图 API。看看这个例子:http://androidattop.blogspot.de/2012/05/splitting-image-into-smaller-chunks-in.html
在上面链接中提供的示例中,提供了一个 ImageView,您可以从中获取图像的位图。然后你可以暂时将拆分的部分保存到位图的数组列表(ArrayList)中。唯一剩下的就是将这些位图提供到 GridView 中。 这是您需要在代码中添加的方法:
private void splitImage(ImageView image, int chunkNumbers) {
//For the number of rows and columns of the grid to be displayed
int rows,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>(chunkNumbers);
//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);
rows = cols = (int) Math.sqrt(chunkNumbers);
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;
}
/* Now the chunkedImages has all the small image chunks in the form of Bitmap class.
* You can do what ever you want with this chunkedImages as per your requirement.
* I pass it to a new Activity to show all small chunks in a grid for demo.
* You can get the source code of this activity from my Google Drive Account.
*/
//Start a new activity to show these chunks into a grid
Intent intent = new Intent(ImageActivity.this, ChunkedImageActivity.class);
intent.putParcelableArrayListExtra("image chunks", chunkedImages);
startActivity(intent);
}
请注意,在上面的示例中,使用了一个 Intent 和一个 putParcelableArrayListExtra 将它们传递到一个新 Activity 中,但您实际上并不需要这样做。因为您可以在布局中声明一个 GridView。然后您可以创建一个扩展 BaseAdapter 类的类并设置图像。最后调用GridView的setAdapter方法。
关于java - Android:如何在不使用 Canvas 的情况下分割图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29783308/