Issue
I want to draw a Drawable on a canvas with a fixed size.
The problem is that the drawable draws itself on the canvas with its instrinsic with and height, and does not take all the space available.
I want to make the drawable fill all the space in canvas, like in an ImageView.
So I have take a look in ImageView source code, and see that matrix is used, I tried below but the drawable is still drawn on the top left corner with its instrinsic size.
For info, my drawable is a PictureDrawable, created from a Picture coming from an SVG file.
Bitmap bitmap = Bitmap.createBitmap(fSize, fSize, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable drawable = svg.createPictureDrawable();
float scale = Math.min((float) fSize / (float) drawable.getIntrinsicWidth(),
(float) fSize / (float) drawable.getIntrinsicHeight());
Matrix matrix = new Matrix();
matrix.setScale(scale, scale);
canvas.setMatrix(matrix);
drawable.draw(canvas);
Thanks.
Solution
You could render the SVG
to a Picture
, and then render that directly to the Canvas
, with something along the lines of:
public Bitmap renderToBitmap(SVG svg, int requiredWidth){
if(requiredWidth < 1) requiredWidth = (int)svg.getIntrinsicWidth();
float scaleFactor = (float)requiredWidth / (float)svg.getIntrinsicWidth();
int adjustedHeight = (int)(scaleFactor * svg.getIntrinsicHeight());
Bitmap bitmap = Bitmap.createBitmap(requiredWidth, adjustedHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(svg.getPicture(), new Rect(0, 0, requiredWidth, adjustedHeight));
return bitmap;
}
The above method will preserve the aspect ratio using the width as the scaling factor. If a value less than one is passed into the method (what you labeled fSize), it will use the intrinsic width of the image when generating the Bitmap
.
Edit: For anyone using AndroidSVG instead of svg-android (like what I'm assuming is being used above), just replace all former occurrences of getIntrinsicWidth(), getIntrinsicHeight(), and getPicture()
with getDocumentWidth(), getDocumentHeight(), and renderToPicture()
, respectively.
Answered By - Cruceo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.