Android中通过反射实现圆角ImageView代码实例
程序员文章站
2022-03-23 14:00:33
private void init(){
paint = new paint(paint.anti_alias_flag);
round...
private void init(){ paint = new paint(paint.anti_alias_flag); roundrect = new rectf(0, 0, getwidth() , getheight()); radius = 40; mporterduffxfermode = new porterduffxfermode(porterduff.mode.src_in) ; }
继承imageview,在构造方法中调用,初始化paint和xfermode。
protected void ondraw(canvas canvas) { int sc = canvas.savelayer(0, 0, getwidth() , getheight(), null, canvas.matrix_save_flag | canvas.clip_save_flag | canvas.has_alpha_layer_save_flag | canvas.full_color_layer_save_flag | canvas.clip_to_layer_save_flag); roundrect.set(0, 0, getwidth(), getheight()); canvas.drawroundrect(roundrect, radius, radius, paint); reflectsetxfermod(); super.ondraw(canvas); canvas.restoretocount(sc); }
重写imageview的ondraw方法,通过xfermode实现圆角
private void reflectsetxfermod(){ drawable drawable = getdrawable(); if(drawable == null){ return; } class bsclass = null; class[] innerclasses = bitmapdrawable.class.getdeclaredclasses(); for(class innerclass :innerclasses) { string name = innerclass.getname(); system.out.println("-----innerclass---"+name); if(name.equals("android.graphics.drawable.bitmapdrawable$bitmapstate")) { bsclass = innerclass; } } if(bsclass!= null){ try { field mpaintfield = bsclass.getdeclaredfield("mpaint"); mpaintfield.setaccessible(true); constantstate constantstate = ((bitmapdrawable)drawable).getconstantstate(); paint paint = (paint)mpaintfield.get(constantstate); paint.setxfermode(mporterduffxfermode); } catch (illegalargumentexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (illegalaccessexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (nosuchfieldexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
通过反射的方法将xfermode设置到bitmapdrawable 里面的内部类bitmapstate里的对象mpaint,用来绘制图片。
上一篇: 相片是怎么成像的?相片的成像原理介绍
下一篇: C++模拟实现vector