import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class GridViewTest extends Activity { private GridView gv=null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gv_init(); setContentView(gv); } /*gv初始化*/ void gv_init(){ gv=new GridView(this); GridView.LayoutParams lp=new GridView.LayoutParams(-1,-1); gv.setLayoutParams(lp); gv.setColumnWidth(90); gv.setNumColumns(GridView.AUTO_FIT); gv.setVerticalSpacing(10); gv.setHorizontalSpacing(10); gv.setAdapter(new ImageAdapter(this)); } /*ImageAdapter*/ public class ImageAdapter extends BaseAdapter { private Context context; //图片源数组 private Integer[] imageInteger = {R.drawable.p00,R.drawable.p01, R.drawable.p02,R.drawable.p03, R.drawable.p04,R.drawable.p05, R.drawable.p06,R.drawable.p07, R.drawable.p08,R.drawable.p09, R.drawable.p10,R.drawable.p11, R.drawable.p12,R.drawable.p13, R.drawable.p14,R.drawable.p15, R.drawable.p16,R.drawable.p17, R.drawable.p18,R.drawable.p19 }; public ImageAdapter(Context c) { context = c; } public int getCount() { return imageInteger.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(context); imageView.setLayoutParams(new GridView.LayoutParams(90,-2)); /*图片缩放处理,如果先设置了iamgeView的大小,则必须注意加载的图片大小不能超出,否则无法显示*/ Bitmap bm = BitmapFactory.decodeResource(context.getResources(),imageInteger[position]); //原始尺寸 int width=bm.getWidth(); int height=bm.getHeight(); //缩放比例 if(width>90){ float scaleWidth=((float)90)/width; float scaleHeight=scaleWidth; // 创建操作图片用的matrix对象 Matrix matrix = new Matrix(); // 缩放图片动作 matrix.postScale(scaleWidth, scaleHeight); //旋转图片 动作 //matrix.postRotate(45); // 创建新的图片 Bitmap resizedBitmap = Bitmap.createBitmap(bm,0,0,width, height,matrix,true); imageView.setImageBitmap(resizedBitmap); }else{ imageView.setImageBitmap(bm); } imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); return imageView; } } }