自定义带倒影效果的TextView
/**
* 最近因为项目需要用到带倒影效果的图片,所以在网上查了一些相关的资料,倒影我只记得好像是在Photoshop中用过,是将原图反转,再加上一些特效实现的,在网上搜索的时候发现了这个自定义的TextView实现,想想自己对Matrix等还不是很了解,这个控件相对来说容易实现,就试着做个,现在记录下来,免得后面忘掉。由于找不到原作者的连接,所以没有贴出来,只知道他是参考的尚弦月的,在这贴出尚弦月博客链接http://www.cnblogs.com/shang53880/p/3549513.html
* 实现倒影效果有以下几步
* 首先拿到原图
* 根据原图创建倒影图
* 根据需要添加两个图之间的间距
* 最后进行图片绘制
*
* @author sunchuang
*
*/
package hmtv.hm.cn.zidingyi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.media.Image;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
/**
* Created by sunchuang on 2017/7/8.
*/
public class ReflectTextView extends android.support.v7.widget.AppCompatTextView {
private Matrix mMatrix;//倒影相关都需要使用Matrix
private Paint mPaint;
public ReflectTextView(Context context) {
this(context,null);
}
public ReflectTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public ReflectTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initData();
}
private void initData() {
//初始化矩阵,设置矩阵变换的形式,并且选择加速模式
mMatrix = new Matrix();
mMatrix.preScale(1,-1);
setLayerType(View.LAYER_TYPE_SOFTWARE,null);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//测量带有倒影后的控件效果通常是高度会增加,这里应该注意要通过getmeasure来获取参数,不然获取不到
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int mWidth = getWidth();
int mHeight = getHeight();
//设置该属性为真可以拿到缓存的图像信息
setDrawingCacheEnabled(true);
Paint paint = new Paint();
paint.setAlpha(100);
Bitmap originalBitmap = Bitmap.createBitmap(getDrawingCache());
//倒影图像
Bitmap reflectBitmap = Bitmap.createBitmap(originalBitmap,0,mHeight/5,mWidth,mHeight/2,mMatrix,false);
canvas.drawBitmap(reflectBitmap,0,mHeight/3f,paint);
if(mPaint==null){
mPaint = new Paint();
LinearGradient shader = new LinearGradient(0,mHeight/2,mWidth,mHeight,0x7fffffff,0x0fffffff, Shader.TileMode.CLAMP);//渐变效果实现
mPaint.setShader(shader);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
}
canvas.drawRect(0,mHeight/2f,mWidth,mHeight,mPaint);
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
buildDrawingCache();
postInvalidate();
destroyDrawingCache();
}
}