package com.example.test; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new MyView(getApplicationContext())); } } class MyView extends View{ public MyView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //原始图片 Bitmap originalBitmap=BitmapFactory.decodeResource(getResources(), R.drawable.img); System.out.println(originalBitmap.getWidth()+" "+originalBitmap.getHeight()); canvas.drawBitmap(originalBitmap, 0,0, null); //下面代码生成原图宽高各为一半的bitmap int pixels[]=new int[originalBitmap.getWidth()*originalBitmap.getHeight()]; //获取原图像素 originalBitmap.getPixels(pixels, 0, originalBitmap.getWidth(), 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight()); int newPixels[]=new int[ (originalBitmap.getWidth()/2) * (originalBitmap.getHeight()/2) ]; //把奇数行奇数列交叉点对应的像素依次放到newPixels中 for (int i = 1; i < originalBitmap.getHeight() ; i+=2) { for (int j = 1; j < originalBitmap.getWidth(); j+=2) { newPixels[ i/2* (originalBitmap.getWidth()/2) +j/2 ]=pixels[ i*originalBitmap.getWidth()+j ]; } } //生成新图片 Bitmap scaleHalfBmp=Bitmap.createBitmap(newPixels, originalBitmap.getWidth()/2, originalBitmap.getHeight()/2, Config.ARGB_8888); canvas.translate(0, originalBitmap.getHeight()+20); canvas.drawBitmap(scaleHalfBmp, 0, 0, null); /////////////////放大///////////////////////////////// int scale2Width=scaleHalfBmp.getWidth()*2; int scale2Height=scaleHalfBmp.getHeight()*2; int scale2pixels[]=new int[scale2Width *scale2Height]; for (int i = 0; i <scale2Height; i++) { for (int j = 0; j < scale2Width; j++) { scale2pixels[i*scale2Width+j]=newPixels[ i/2*scaleHalfBmp.getWidth() + j/2 ]; } } // for (int i = 0; i < scaleHalfBmp.getHeight(); i++) { // for (int j = 0; j < scaleHalfBmp.getWidth(); j++) { // scale2pixels[ i*2*scale2Width+ j*2 ]=newPixels[i*scaleHalfBmp.getWidth()+j]; // } // } Bitmap bmp=Bitmap.createBitmap(scale2pixels, scale2Width, scale2Height, Config.ARGB_8888); canvas.translate(0, scaleHalfBmp.getHeight()+10); canvas.drawBitmap(bmp, 0, 0, null); } }