[英]How to make a drawable fits canvas
I want to draw a Drawable on a canvas with a fixed size. 我想在固定大小的画布上绘制一个Drawable。
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. 我想使drawable填充画布中的所有空间,就像在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. 因此,我看了ImageView源代码,看到使用了矩阵,我在下面尝试过,但是drawable仍以其内在大小绘制在左上角。
For info, my drawable is a PictureDrawable, created from a Picture coming from an SVG file. 有关信息,我的drawable是一个PictureDrawable,它是根据SVG文件中的图片创建的。
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. 谢谢。
You could render the SVG
to a Picture
, and then render that directly to the Canvas
, with something along the lines of: 您可以将
SVG
渲染为Picture
,然后将其直接渲染到Canvas
,其方式如下:
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
. 如果将小于1的值传递给方法(标记为fSize),则在生成
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. 编辑:对于使用AndroidSVG而不是svg-android的任何人(例如我在上面使用的假设),只需将
getIntrinsicWidth(), getIntrinsicHeight(), and getPicture()
所有以前出现的getIntrinsicWidth(), getIntrinsicHeight(), and getPicture()
替换为getDocumentWidth(), getDocumentHeight(), and renderToPicture()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.