在我的ImageView onDraw
中,我正在努力将Drawable对象转换为Bitmap(尊重缩放)。我正在加载一个SVG文件作为PictureDrawable。然后我尝试使用BitmapShader将圆角应用于图像。为了做到这一点,我必须将Drawable转换为Bitmap。它基本上可以工作,但我没有理解缩放程序。
Bitmap bitmap = Bitmap.createBitmap(
picture.getIntrinsicWidth(),
picture.getIntrinsicHeight(),
Bitmap.Config.ARGB_8888
)
Canvas canvas = new Canvas( bitmap )
// Scaling the Canvas appears to work ...
canvas.concat( getImageMatrix() )
canvas.drawPicture(
picture.getPicture,
// ... however this will not fill the viewport, as the getWidth and getHeight
// values do not reflect the scaling
new RectF( 0, 0, canvas.getWidth(), canvas.getHeight() )
)
paint.setShader( new BitmapShader( bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP ) )
canvas.drawRoundRect(
new RectF( 0, 0, bitmap.getWidth(), bitmap.getHeight() ),
radius,
radius,
paint
)
centerCrop缩放的错误渲染示例:
除了上面代码注释中描述的问题之外,我想知道是否可以使用绘图操作(例如clipPath)而不是这种大量的Bitmap转换来屏蔽Picture / SVG文件。但当然,它必须是抗锯齿的。
代码最初是用Scala编写的,并且松散地翻译成了Java for SO,所以请忽略任何语法错误
答案 0 :(得分:1)
通过pskink对类似问题的回答(Make Image view rounded (not the image)),我根据saveLayer方法(稍加修改)得出了以下解决方案。
@Override
public void onDraw( Canvas canvas )
{
Paint paint1 = new Paint( Paint.ANTI_ALIAS_FLAG )
Paint paint2 = new Paint()
paint2.setXfermode( new PorterDuffXfermode( Mode.SRC_IN ) )
Drawable drawable = getDrawable()
RectF rectangle = new RectF()
rectangle.set( drawable.getBounds() )
getImageMatrix.mapRect( rectangle )
rectangle.offset( getPaddingLeft(), getPaddingTop() )
// Prevent radius being drawn out of canvas bounds
rectangle.intersect( new RectF( 0, 0, canvas.getWidth(), canvas.getHeight() ) )
int restore = canvas.saveLayer( rectangle, null, Canvas.ALL_SAVE_FLAG )
canvas.drawRoundRect( rectangle, radius.getValue(), radius.getValue(), paint1 )
canvas.saveLayer( rectangle, paint2, Canvas.ALL_SAVE_FLAG )
super.onDraw( canvas )
canvas.restoreToCount( restore )
}
上面的代码忽略了类级别的对象缓存,并忽略了getDrawable()中的NPE。