android 画图之bitmap(一)

要把一个Bitmap画到View上,必须用到的类有android.graphics.Canvas,和android.graphics.Bitmap。方法很简单,在View里面,重载onDraw(Canvascanvas)方法,然后用canvas.drawBitmap()方法,将其画在屏幕上。

代码:

public class ViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }
    
    public class MyView extends View {
    	
    	private Bitmap mBitmap;
    	
    	private int mScreenWidth;
    	private int mScreenHeight;
    	
    	public MyView(Context context) {
    		super(context);
    		initialize();
    	}

    	private void initialize() {
    		DisplayMetrics dm = getResources().getDisplayMetrics();
    		mScreenWidth = dm.widthPixels;
    		mScreenHeight = dm.heightPixels;
    		
//    		Bitmap bmp 
    		mBitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap();
//    		mBitmap = Bitmap.createScaledBitmap(bmp, mScreenWidth, mScreenHeight, true);		
    	}
    	
    	@Override protected void onDraw(Canvas canvas) {
//    		super.onDraw(canvas);  //当然,如果界面上还有其他元素需要绘制,只需要将这句话写上就行了。
    		canvas.drawBitmap(mBitmap, 0, 0, null);
    	}
    }
}

原图:android 画图之bitmap(一)_第1张图片


程序里显示效果:

现在我们来做点效果:

上面是直接将原图画在屏幕上,没有任何处理,我们试着将图片拉伸以填满整个屏幕。(电脑桌面有平铺,拉伸,居中等操作)

代码:

public class ViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }
    
    public class MyView extends View {
    	
    	private Bitmap mBitmap;
    	
    	private int mScreenWidth;
    	private int mScreenHeight;
    	
    	public MyView(Context context) {
    		super(context);
    		initialize();
    	}

    	private void initialize() {
    		DisplayMetrics dm = getResources().getDisplayMetrics();
    		mScreenWidth = dm.widthPixels;
    		mScreenHeight = dm.heightPixels;
    		
    		Bitmap bmp = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap();
    		mBitmap = Bitmap.createScaledBitmap(bmp, mScreenWidth, mScreenHeight, true);		
    	}
    	
    	@Override protected void onDraw(Canvas canvas) {
//    		super.onDraw(canvas);  //当然,如果界面上还有其他元素需要绘制,只需要将这句话写上就行了。
    		canvas.drawBitmap(mBitmap, 0, 0, null);
    	}
    }
}



是不是拉伸了啊,铺满了整个屏幕啊

参考资料:

http://chroya.iteye.com/blog/710210



你可能感兴趣的:(android,null,Class)