利用DashPathEffect画具有动画效果的矩形动态头像边框

来源:互联网 发布:中国机床 知乎 编辑:程序博客网 时间:2024/05/16 07:56
package com.example.demo;import android.R.integer;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.DashPathEffect;import android.graphics.Paint;import android.graphics.Path;import android.graphics.PathEffect;import android.graphics.Paint.Style;import android.util.AttributeSet;import android.widget.ImageView;public class CustomView extends ImageView{//画笔private Paint linePaint;//路径效果private PathEffect pathEffect;//路径对象private Path mPath;private float phase;public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);// TODO Auto-generated constructor stub} public CustomView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stublinePaint=new Paint();}public CustomView(Context context) {super(context);// TODO Auto-generated constructor stub}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);pathEffect=new DashPathEffect(new float[] { 10, 15, 20, 10 },                  phase);linePaint.setAntiAlias(true);//设置抗锯齿linePaint.setColor(Color.RED);//画笔颜色linePaint.setStyle(Style.STROKE);//画笔样式linePaint.setStrokeWidth(2);//画笔宽度linePaint.setPathEffect(pathEffect);//路径动画mPath=new Path();mPath.moveTo(0, 0);//起点mPath.lineTo(getRight()-20, 0);mPath.lineTo(getRight()-20, getBottom()-20);mPath.lineTo(0, getBottom()-20);mPath.close();canvas.translate(10, 10);  canvas.drawPath(mPath, linePaint);canvas.translate(10, 10);  }public void setPhase(float phase){this.phase=phase;        postInvalidate(); }}
MainActivity:public class MainActivity extends Activity {private CustomView customView;private float pahse;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        customView=(CustomView) findViewById(R.id.customView);        handler.sendEmptyMessage(0);    }    Handler handler=new Handler(){    public void handleMessage(android.os.Message msg) {    if(msg.what==0){    pahse+=1;    customView.setPhase(pahse);    handler.sendEmptyMessage(0);    }    };    };    }

布局:<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <com.example.demo.CustomView        android:id="@+id/customView"        android:layout_width="200dp"        android:layout_height="200dp"        android:src="@drawable/ic_launcher"        android:background="#ffff00"         /></RelativeLayout>


0 0
原创粉丝点击