一:要达到的效果
二:布局使用了GridLayout(五列三行)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.kirito.puzzlegame.MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridLayout
android:id="@+id/gl"
android:columnCount="3"
android:rowCount="5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</HorizontalScrollView>
</ScrollView>
</RelativeLayout>
三:以二维数组来表示图片切割的各个部分,使用createBitmap方法切割图片,使用gridlayout的addview方法把图片块添加进去
package com.example.kirito.puzzlegame;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ImageView ivs[][] = new ImageView[5][3];
private GridLayout gl;
private ImageView null_iv;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gl = (GridLayout) findViewById(R.id.gl);
//从drawable下获取图片资源并将其转为bitmap
Bitmap bm = ((BitmapDrawable)getResources().getDrawable(R.drawable.a)).getBitmap();
int bm_height = bm.getHeight() / 5;
int bm_width = bm.getWidth() / 3;
for (int i = 0; i < ivs.length; i++) {
for (int j = 0; j < ivs[0].length; j++) {
ivs[i][j] = new ImageView(this);
//通过bitmap的createBitmap方法来切割图片,把完整图片分割成五行三列
/**
* createBitmap方法解析
* Bitmap.createBitmap(source, 60, 0, 480, 260); // 320 - 60 = 260
Basically, you are drawing from x = 60, y = 0 to x = 480 + 60, y = 260 on a Bitmap
*/
//完整分割图片
Bitmap bp = Bitmap.createBitmap(bm,j * bm_width,i * bm_height,bm_width,bm_height);
ivs[i][j].setImageBitmap(bp);
//这种均等切割为正方形的方式,最终只会显示原图的一部分,即把原图左上角部分的正方形切割下来,其他的就舍弃了
/*Bitmap bp = Bitmap.createBitmap(bm,j * bm_height,i * bm_height,bm_height,bm_height);
ivs[i][j].setImageBitmap(bp);*/
ivs[i][j].setPadding(2,2,2,2);
}
}
for (int i = 0; i < ivs.length; i++) {
for (int j = 0; j < ivs[0].length; j++) {
//通过给gridview添加切割好的小图片
gl.addView(ivs[i][j]);
}
}
}
}