Android中通过反射实现圆角ImageView代码实例
程序员文章站
2022-06-23 10:15:15
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,用来绘制图片。
推荐阅读
-
Android通过手势实现的缩放处理实例代码
-
android实现搜索功能并将搜索结果保存到SQLite中(实例代码)
-
php中通过Ajax如何实现异步文件上传的代码实例
-
Android中实现图文并茂的按钮实例代码
-
Android中通过ImageSwitcher实现相册滑动查看照片功能(附代码下载)
-
在CSS中映射鼠标位置并实现通过鼠标移动控制页面元素效果(实例代码)
-
Android中实现长按照片弹出右键菜单功能的实例代码
-
Android中通过反射实现圆角ImageView代码实例
-
Android中通过Java代码实现ScrollView滚动视图-以歌词滚动为例
-
php中通过curl模拟登陆discuz论坛的实现代码_php实例