Android Xfermode 实战 实现圆形、圆角图片

来源:互联网 发布:孚盟软件logo 编辑:程序博客网 时间:2024/04/29 21:45

转自:http://blog.csdn.net/lmj623565791/article/details/42094215,本文出自:【张鸿洋的博客】

1、概述

其实这篇本来准备Android BitmapShader 实战 实现圆形、圆角图片放到一篇里面,结果由于篇幅原因就独立出来了~在很久以前也写过一个利用Xfermode 实现圆形、圆角图片的,但是那个继承的是View,其实继承ImageView能方便点,最起码省去了onMeasure里面自己去策略,以及不需要自己去提供设置图片的方法,最主要的是大家对ImageView的API会比较熟悉,用起来会比较顺手。

好了,本篇就当是个记录了~~~电脑上代码放几天就找不到了,还是放博客里面,有需要自己过来看看~~~

2、原理


原理就不多说了,这张图在我博客里出现的次数大概有3次以上了,我们这次使用的模式DST_IN;也就是先绘制图片,再绘制形状了~~

3、Xfermode实战

1、自定义属性

首先依然是自定义属性,和上篇一致。

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   
  4.     <attr name="borderRadius" format="dimension" />  
  5.     <attr name="type">  
  6.         <enum name="circle" value="0" />  
  7.         <enum name="round" value="1" />  
  8.     </attr>  
  9.     
  10.   
  11.     <declare-styleable name="RoundImageViewByXfermode">  
  12.         <attr name="borderRadius" />  
  13.         <attr name="type" />  
  14.     </declare-styleable>  
  15.   
  16. </resources>  

2、构造中获取属性

[java] view plaincopy
  1. public class RoundImageViewByXfermode extends ImageView  
  2. {  
  3.   
  4.     private Paint mPaint;  
  5.     private Xfermode mXfermode = new PorterDuffXfermode(Mode.DST_IN);  
  6.     private Bitmap mMaskBitmap;  
  7.   
  8.     private WeakReference<Bitmap> mWeakBitmap;  
  9.   
  10.     /** 
  11.      * 图片的类型,圆形or圆角 
  12.      */  
  13.     private int type;  
  14.     public static final int TYPE_CIRCLE = 0;  
  15.     public static final int TYPE_ROUND = 1;  
  16.     /** 
  17.      * 圆角大小的默认值 
  18.      */  
  19.     private static final int BODER_RADIUS_DEFAULT = 10;  
  20.     /** 
  21.      * 圆角的大小 
  22.      */  
  23.     private int mBorderRadius;  
  24.   
  25.     public RoundImageViewByXfermode(Context context)  
  26.     {  
  27.         this(context,null);  
  28.   
  29.         mPaint = new Paint();  
  30.         mPaint.setAntiAlias(true);  
  31.     }  
  32.   
  33.     public RoundImageViewByXfermode(Context context, AttributeSet attrs)  
  34.     {  
  35.         super(context, attrs);  
  36.   
  37.         mPaint = new Paint();  
  38.         mPaint.setAntiAlias(true);  
  39.   
  40.         TypedArray a = context.obtainStyledAttributes(attrs,  
  41.                 R.styleable.RoundImageViewByXfermode);  
  42.   
  43.         mBorderRadius = a.getDimensionPixelSize(  
  44.                 R.styleable.RoundImageViewByXfermode_borderRadius, (int) TypedValue  
  45.                         .applyDimension(TypedValue.COMPLEX_UNIT_DIP,  
  46.                                 BODER_RADIUS_DEFAULT, getResources()  
  47.                                         .getDisplayMetrics()));// 默认为10dp  
  48.         Log.e("TAG", mBorderRadius+"");  
  49.         type = a.getInt(R.styleable.RoundImageViewByXfermode_type, TYPE_CIRCLE);// 默认为Circle  
  50.   
  51.         a.recycle();  
  52.     }  

获取自定义属性,然后还写些成员变量~~

3、onMeasure

[java] view plaincopy
  1. @Override  
  2.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  3.     {  
  4.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  5.   
  6.         /** 
  7.          * 如果类型是圆形,则强制改变view的宽高一致,以小值为准 
  8.          */  
  9.         if (type == TYPE_CIRCLE)  
  10.         {  
  11.             int width = Math.min(getMeasuredWidth(), getMeasuredHeight());  
  12.             setMeasuredDimension(width, width);  
  13.         }  
  14.   
  15.     }  

在onMeasure中,如果是圆形则重新设置view大小。

4、onDraw

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @SuppressLint("DrawAllocation")  
  2.     @Override  
  3.     protected void onDraw(Canvas canvas)  
  4.     {  
  5.         //在缓存中取出bitmap  
  6.         Bitmap bitmap = mWeakBitmap == null ? null : mWeakBitmap.get();  
  7.   
  8.         if (null == bitmap || bitmap.isRecycled())  
  9.         {  
  10.             //拿到Drawable  
  11.             Drawable drawable = getDrawable();  
  12.             //获取drawable的宽和高  
  13.             int dWidth = drawable.getIntrinsicWidth();  
  14.             int dHeight = drawable.getIntrinsicHeight();  
  15.   
  16.             if (drawable != null)  
  17.             {  
  18.                 //创建bitmap  
  19.                 bitmap = Bitmap.createBitmap(getWidth(), getHeight(),  
  20.                         Config.ARGB_8888);  
  21.                 float scale = 1.0f;  
  22.                 //创建画布  
  23.                 Canvas drawCanvas = new Canvas(bitmap);  
  24.                 //按照bitmap的宽高,以及view的宽高,计算缩放比例;因为设置的src宽高比例可能和imageview的宽高比例不同,这里我们不希望图片失真;  
  25.                 if (type == TYPE_ROUND)  
  26.                 {  
  27.                     // 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;  
  28.                     scale = Math.max(getWidth() * 1.0f / dWidth, getHeight()  
  29.                             * 1.0f / dHeight);  
  30.                 } else  
  31.                 {  
  32.                     scale = getWidth() * 1.0F / Math.min(dWidth, dHeight);  
  33.                 }  
  34.                 //根据缩放比例,设置bounds,相当于缩放图片了  
  35.                 drawable.setBounds(00, (int) (scale * dWidth),  
  36.                         (int) (scale * dHeight));  
  37.                 drawable.draw(drawCanvas);  
  38.                 if (mMaskBitmap == null || mMaskBitmap.isRecycled())  
  39.                 {  
  40.                     mMaskBitmap = getBitmap();  
  41.                 }  
  42.                 // Draw Bitmap.  
  43.                 mPaint.reset();  
  44.                 mPaint.setFilterBitmap(false);  
  45.                 mPaint.setXfermode(mXfermode);  
  46.                 //绘制形状  
  47.                 drawCanvas.drawBitmap(mMaskBitmap, 00, mPaint);  
  48.                 mPaint.setXfermode(null);  
  49.                 //将准备好的bitmap绘制出来  
  50.                 canvas.drawBitmap(bitmap, 00null);  
  51.                 //bitmap缓存起来,避免每次调用onDraw,分配内存  
  52.                 mWeakBitmap = new WeakReference<Bitmap>(bitmap);  
  53.             }  
  54.         }  
  55.         //如果bitmap还存在,则直接绘制即可  
  56.         if (bitmap != null)  
  57.         {  
  58.             mPaint.setXfermode(null);  
  59.             canvas.drawBitmap(bitmap, 0.0f, 0.0f, mPaint);  
  60.             return;  
  61.         }  
  62.   
  63.     }  
  64.     /** 
  65.      * 绘制形状 
  66.      * @return 
  67.      */  
  68.     public Bitmap getBitmap()  
  69.     {  
  70.         Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(),  
  71.                 Bitmap.Config.ARGB_8888);  
  72.         Canvas canvas = new Canvas(bitmap);  
  73.         Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);  
  74.         paint.setColor(Color.BLACK);  
  75.   
  76.         if (type == TYPE_ROUND)  
  77.         {  
  78.             canvas.drawRoundRect(new RectF(00, getWidth(), getHeight()),  
  79.                     mBorderRadius, mBorderRadius, paint);  
  80.         } else  
  81.         {  
  82.             canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2,  
  83.                     paint);  
  84.         }  
  85.   
  86.         return bitmap;  
  87.     }  

在onDraw中拿到drawable,然后获取drawable的宽和高,根据当前的type和view的宽和高,进行适当的缩放。具体原理:参考上篇的matrix的scale计算,原理一致。

然后就是设置Xfermode,getBitmap会根据type返回图形,直接绘制到内存中的bitmap上即可。最后把bitmap缓存起来,避免每次onDraw都分配内存和重启绘图。

大家可以进行扩展type,绘制心形、三角形什么的,直接在getBitmap里面添加分支就可以。

最后记得invalidate中做一些处理:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @Override  
  2.     public void invalidate()  
  3.     {  
  4.         mWeakBitmap = null;  
  5.         if (mMaskBitmap != null)  
  6.         {  
  7.             mMaskBitmap.recycle();  
  8.             mMaskBitmap = null;  
  9.         }  
  10.         super.invalidate();  
  11.     }  

主要是因为我们缓存了,当调用invalidate时,将缓存清除。

4、布局文件及效果图

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     xmlns:zhy="http://schemas.android.com/apk/res/com.zhy.variousshapeimageview"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="wrap_content" >  
  6.   
  7.     <LinearLayout  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="match_parent"  
  10.         android:orientation="vertical" >  
  11.   
  12.   
  13.         <com.zhy.view.RoundImageViewByXfermode  
  14.             android:layout_width="130dp"  
  15.             android:layout_height="130dp"  
  16.             android:layout_margin="10dp"  
  17.             android:src="@drawable/qiqiu" >  
  18.         </com.zhy.view.RoundImageViewByXfermode>  
  19.   
  20.         <com.zhy.view.RoundImageViewByXfermode  
  21.             android:layout_width="wrap_content"  
  22.             android:layout_height="wrap_content"  
  23.             android:layout_margin="10dp"  
  24.             android:src="@drawable/aa"  
  25.             zhy:borderRadius="30dp"  
  26.             zhy:type="round" >  
  27.         </com.zhy.view.RoundImageViewByXfermode>  
  28.   
  29.         <com.zhy.view.RoundImageViewByXfermode  
  30.             android:layout_width="wrap_content"  
  31.             android:layout_height="wrap_content"  
  32.             android:layout_margin="10dp"  
  33.             android:src="@drawable/aa"  
  34.             zhy:type="circle" >  
  35.         </com.zhy.view.RoundImageViewByXfermode>  
  36.   
  37.         <com.zhy.view.RoundImageViewByXfermode  
  38.             android:layout_width="40dp"  
  39.             android:layout_height="40dp"  
  40.             android:layout_margin="10dp"  
  41.             android:src="@drawable/aa"  
  42.             zhy:type="circle" >  
  43.         </com.zhy.view.RoundImageViewByXfermode>  
  44.   
  45.     </LinearLayout>  
  46.   
  47. </ScrollView>  

效果图:



好了,比较简单~~

声明下:本例参考了:https://github.com/MostafaGazar/CustomShapeImageView ;不过对其中的部分代码进行了改变,比如CustomShapeImageView如果图片为长方形,但是设置为circle类型,效果依然是矩形;以及会对bitmap比例和view比例不一致的直接进行压缩,类似fitxy的效果~~~主要对这两点进行了修改~~当然了,该案例比本博客功能要强大,看名字也知道,支持很多形状,以及支持SVG~大家自行进行参考~



源码点击下载

0 0
原创粉丝点击