服务器之家

服务器之家 > 正文

Android中通过反射实现圆角ImageView代码实例

时间:2021-03-18 15:19     来源/作者:Android教程网
?
1
2
3
4
5
6
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。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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实现圆角

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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,用来绘制图片。

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部