I'm trying to use vector drawables to draw into canvas. Everything is fine and dandy till I rotate the canvas object by 90 or 270 degrees. Closer I get to 90 or 270 degrees, more blurry the drawable shown in canvas appears. Finally at 90 or 270 degrees, the vector drawable on canvas disappears completely. Is there some sort of fix or workaround for this? Or should I approach drawing into canvas with svg's with some other library? Thanks!
Here's the code:
public class CanvasView extends View {
private static final String TAG = "CanvasView";
private VectorDrawableCompat vectorDrawableCompat;
private int angle;
public CanvasView(Context context) {
super(context);
init();
}
public CanvasView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CanvasView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
vectorDrawableCompat = VectorDrawableCompat.create(getResources(),
R.drawable.ic_android_black_24dp, null);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
vectorDrawableCompat.setBounds((getWidth()/2) - 50, (getHeight()/2) - 50, (getWidth()/2) + 50, (getHeight()/2) + 50);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.rotate(angle, getWidth()/2, getHeight()/2);
vectorDrawableCompat.draw(canvas);
canvas.restore();
}
public void setAngle(int angle){
Log.i(TAG, "setAngle: " + angle);
this.angle = angle;
invalidate();
}
}
Here's the project: https://github.com/danskiess/VectorTest
This has been fixed in the android framework. https://code.google.com/p/android/issues/detail?id=192413
One possible workaround for this rotation case could be just draw the VectorDrawable into a Bitmap, then rotate the bitmap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With