自定义View之绘制圆环

来源:互联网 发布:淘宝店铺转让受骗案例 编辑:程序博客网 时间:2024/04/30 10:31

一、RingView

自定义的view,构造器必须重写,至于重写哪个方法,参考如下:

①如果需要改变View绘制的图像,那么需要重写OnDraw方法。(这也是最常用的重写方式。)

②如果需要改变view的大小,那么需要重写OnMeasure方法。

③如果需要改变View的(在父控件的)位置,那么需要重写OnLayout方法。

④根据上面三种不同的需要你可以组合出多种重写方案,你懂的。

注释信息代码中比较详细。

package com.example.customerviewdemo2;import android.content.Context;import android.graphics.Canvas;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;public class RingView extends View {private final  Paint paint;private final Context context;public RingView(Context context) {this(context, null);}public RingView(Context context, AttributeSet attrs) {super(context, attrs);this.context = context;this.paint = new Paint();this.paint.setAntiAlias(true); //消除锯齿this.paint.setStyle(Paint.Style.STROKE); //绘制空心圆 }@Overrideprotected void onDraw(Canvas canvas) {// TODO Auto-generated method stubint center = getWidth()/2;int innerCircle = dip2px(context, 83); //设置内圆半径int ringWidth = dip2px(context, 10); //设置圆环宽度//绘制内圆this.paint.setARGB(155, 167, 190, 206);this.paint.setStrokeWidth(10);//设置内圆的厚度canvas.drawCircle(center,center, innerCircle, this.paint);//以该圆为半径向内外扩展至厚度为10px//绘制圆环,设置圆环的颜色修改画笔的颜色//this.paint.setARGB(255, 212 ,225, 233);this.paint.setARGB(255, 255, 0, 0);this.paint.setStrokeWidth(ringWidth);//设置圆环宽度canvas.drawCircle(center,center, innerCircle+1+ringWidth/2, this.paint);//圆环宽度为中间圆//绘制外圆this.paint.setARGB(155, 167, 190, 206);this.paint.setStrokeWidth(2);canvas.drawCircle(center,center, innerCircle+ringWidth, this.paint);super.onDraw(canvas);}/** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */public static int dip2px(Context context, float dpValue) {final float scale = context.getResources().getDisplayMetrics().density;return (int) (dpValue * scale + 0.5f);}}

二、引用该View的代码

<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"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />    <com.example.customerviewdemo2.RingView        android:layout_width="300dp"        android:layout_height="300dp" >    </com.example.customerviewdemo2.RingView></RelativeLayout>
三、效果如下



0 0
原创粉丝点击