AndroidSVG图像上的模糊边缘
问题描述:
我想在android上显示条码。作为输入,我得到SVG字符串。作为一个SVG库我使用AndroidSVG。我使用图书馆网站的示例代码,一切似乎都很好。但是当我放大图像时,我会看到扭曲的边缘(Anti-alias?)。我试图禁用所有的标志。但图像边缘仍然模糊。我的代码有什么问题?AndroidSVG图像上的模糊边缘
代码:
private void loadQRCode(String svgString) {
SVG svg = null;
try {
svg = SVG.getFromString(svgString);
} catch (SVGParseException e) {
e.printStackTrace();
}
if (svg.getDocumentWidth() != -1) {
int widthPx = Utils.pxFromDp(400);
int heightDp = Utils.pxFromDp(300);
svg.setDocumentWidth(widthPx);
svg.setDocumentHeight(heightDp);
int width = (int) Math.ceil(svg.getDocumentWidth());
int height = (int) Math.ceil(svg.getDocumentHeight());
Bitmap newBM = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas bmcanvas = new Canvas(newBM);
final DrawFilter filter = new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG| Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG, 0);
bmcanvas.setDrawFilter(filter);
barcode.setLayerType(View.LAYER_TYPE_SOFTWARE,null);
bmcanvas.drawRGB(255, 255, 255);
svg.renderToCanvas(bmcanvas);
barcode.setImageBitmap(newBM);
}
}
答
如果条的边缘不撒谎像素边界究竟,你会得到消除锯齿。在高分辨率屏幕上,这通常不会显示。
然而,在你的代码,你渲染SVG为位图和位图设置为一个ImageView的。如果该ImageView的尺寸大于位图 - 即。大于400 x 300,那么该位图中的消除锯齿的像素可能会变得更大并因此更明显。
一种解决方案是避免使用位图。改为使用Picture
/PictureDrawable
。这样,条码将以最高质量呈现,无论其尺寸如何。正如矢量图形应该是。
按照此页面上的例子:
http://bigbadaboom.github.io/androidsvg/use_with_ImageView.html
所以,你的代码应该看起来可能像下面这样:
private void loadQRCode(String svgString) {
try {
SVG svg = SVG.getFromString(svgString);
barcode.setLayerType(View.LAYER_TYPE_SOFTWARE,null);
Drawable drawable = new PictureDrawable(svg.renderToPicture());
barcode.setImageDrawable(drawable);
} catch (SVGParseException e) {
e.printStackTrace();
}
}
如果由于某种原因,你需要使用位图 - 说不定您正在缓存它们或什么 - 然后你应该观察ImageView
大小的变化,然后重新创建新大小的位图。因此,位图总是与它所分配的ImageView
相同。
将SVG转换为位图以便显示,您需要提高分辨率以在缩放时保留清晰度。 – Duopixel