paint的使用
<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.itheima.wave28.MyRring android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
package com.itheima.wave28; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.os.Handler; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class MyRring extends View{ /** * 圆环圆心的X坐标 */ private int cx; /** * 圆环圆心的Y坐标 */ private int cy; private Paint paint; /** * 圆环的半径 */ private float radius; /** * 线条的厚度 */ private float strokeWidth; public MyRring(Context context, AttributeSet attrs) { super(context, attrs); initView(); } private void initView() { //初始化paint paint = new Paint(); paint.setAntiAlias(true); // 抗矩齿 paint.setColor(Color.RED); paint.setStyle(Style.STROKE); //刻画,画线条 默认的是Fill状态,就是填充颜色 paint.setStrokeWidth(strokeWidth); //设置条线的厚度 paint.setAlpha(255); //设置透明度 ,0--255 0代表完全透明 // this.radius =0; strokeWidth = 0; } @Override /** * 绘制我们的内容 */ protected void onDraw(Canvas canvas) { super.onDraw(canvas); /** * 绘制圆环 * 由onTouchEvent获取圆心 就是点击下去时的位置 */ canvas.drawCircle(cx, cy, radius, paint); } @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 点击,获得圆环的中心 cx = (int) event.getX(); cy = (int) event.getY(); //初始化画笔 initView(); handler.sendEmptyMessage(0); break; } return true; } /* * 刷新状态 */ private void flushState() { this.radius+=10; this.strokeWidth = radius/4; paint.setStrokeWidth(strokeWidth); int nextAlpha = paint.getAlpha()-20; //小于20再减就负数了 所以直接等于0即可 if(nextAlpha<=20){ nextAlpha = 0; } paint.setAlpha(nextAlpha); } private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { //刷新状态 flushState(); // 刷新页面 执行onDraw()方法绘制 invalidate(); if(paint.getAlpha() !=0){ //第二参数是延迟时间 handler.sendEmptyMessageDelayed(0, 100); } }; }; @Override /** * 大小的测量按系统的默认规则 * 默认规则就是在xml布局里面定义的 * android:layout_width="match_parent" * android:layout_height="match_parent" */ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
时间: 2024-11-02 10:04:00