题目来自:《android高薪之路—android程序员面试宝典》一书 ,只是为了个人学习方便
题目:在android工程的res/drawable目录中有一个android.png图像文件,如何将该图像显示在View上
直接代码:
- package com.app;
- import java.io.InputStream;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.BitmapFactory.Options;
- import android.graphics.Canvas;
- import android.graphics.Paint;
- import android.graphics.drawable.Drawable;
- import android.view.View;
- public class GetBitmapView extends View{
- public GetBitmapView(Context context) {
- super(context);
- }
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- Paint paint = new Paint();
- InputStream is = getResources().openRawResource(R.drawable.android);
- Options opts = new Options();
- opts. inSampleSize=2;
- Bitmap bitmap = BitmapFactory. decodeStream(is, null, opts);
- canvas.drawBitmap(bitmap, 10, 10, paint);
- Drawable drawable = getResources().getDrawable(R.drawable.android);
- drawable.setBounds(50, 350, 180, 420);
- drawable.setAlpha(100);
- drawable.draw(canvas);
- }
- }