开发者

Drawing Bitmap in Android?

My project is about image processing in android.I have a bitmap that I have loaded from a resource file (an PNG image). I want to draw it. But I couldn't. Here my code snippet:

mB = BitmapFactory.decodeResource(getResources(), R.drawable.picture);
Canvas c = new Canvas(mB);
Paint p = new Paint(); 
c.drawBitmap(mB,0,0,p); 

it didn't work. Is the code true? .Is there any 开发者_开发问答thing more that I must do?


You should use an ImageView instead and load it by

imageView.setImageResource(R.drawable.picture);

If you want to manually draw it with a Canvas, you have to use a canvas that is passed into a draw() method and implement a Custom View.

Update to add example CustomView:

public class CustomView extends View {
    private Paint mPaint;
    private Drawable mDrawable;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mDrawable = context.getResources().getDrawable(R.drawable.some_drawable);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mDrawable.draw(canvas);
    }
}


There are a couple of things you are missing.

First, I think you're misunderstanding the Canvas(Bitmap b) constructor. The Bitmap passed in there is one that the Canvas will draw into. This could be just a new Bitmap that you constructed.

Second, it is recommended that you use the Canvas that is passed to you in your View's onDraw method. Presumably that View is one from your Activity, either fetched from your XML layout via findViewById or constructed and passed to setContentView in the Activity's onCreate() method.

So, you are going to have to subclass View and override the onDraw method to get your drawing done. Something like:

public class MyView extends View {
  @Override
  public void onDraw (Canvas c) {
     Bitmap mB = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.picture);
     c.drawBitmap(mB, 0, 0, null);
  }
}

Then, in your Activity, you'll need to create an instance of your new View and pass it to the Activity via setContentView:

public class MyActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mv = new MyView(this);
    setContentView(mv);
}

You can instead call the setContentView(View v, ViewGroup.LayoutParameters lp) overload if you want to set up the LayoutParameters.

I haven't tested any of this, but it should at least get you on the right path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜