Reputation: 1637
Im trying to draw a jpg to a canvas in onDraw() however the Bitmap type doesnt seem to be drawable (doesn't have the .draw method). My goal is to have a jpeg that is movable on the screen with a touch/drag. How do I need to draw this?
Here is my constructor (where i pass the image path to the view)
public TouchViewClass(Context context, AttributeSet attrs, int defStyle, String picPath) {
super(context, attrs, defStyle);
this.picPath=picPath;
}
Here is my onDraw
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Bitmap myImg = BitmapFactory.decodeFile(picPath);
canvas.save();
canvas.translate(mPosX, mPosY);
//Here is where the bitmap should be drawn
canvas.restore();
}
Upvotes: 0
Views: 1474
Reputation: 2085
I would change the faulty implementation exposed to something like:
public class TouchViewClass extends View{
private Bitmap myImg;
private float mPosX = 0;
private float mPosY = 0;
private Paint paint = new Paint();
public float getmPosX() {
return mPosX;
}
public void setmPosX(float mPosX) {
this.mPosX = mPosX;
}
public float getmPosY() {
return mPosY;
}
public void setmPosY(float mPosY) {
this.mPosY = mPosY;
}
/**
* So you can inflate from XML
* @param context
* @param attrs
*/
public TouchViewClass(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* So you can create in code
* @param context
* @param attrs
* @param picPath
*/
public TouchViewClass(Context context, AttributeSet attrs, String picPath) {
super(context, attrs);
setPicPath(context, picPath);
}
public void setPicPath(Context context, String picPath){
if(!TextUtils.isEmpty(picPath)){
myImg = BitmapFactory.decodeFile(picPath);
}else{
Resources resources = context.getResources();
myImg = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(myImg, mPosX, mPosY, paint);
}
}
Upvotes: 0
Reputation: 20934
First of all, I would not recommend decoding file to bitmap in onDraw()
. This method is called every single frame, so your draw process is going to be extremely slow. You need to decode your file beforehand (in your case in your constructor) and reuse this bitmap in onDraw
.
As for actual drawing bitmap, you can easily draw bitmap by calling Canvas.drawBitmap() method.
So basically you don't even need to translate canvas - you can specify destination directly:
canvas.drawBitmap(bmp, mPosX, mPosY, null);
Upvotes: 4