1.自定义View画一个圆形代码如下:
package com.zhjy.measureview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
/**
* @author :huangxianfeng on 2016/10/13.
* 画出一个圆形
* 1.继承View和ViewGroup的时候,在布局中设置padding属性是不起作用的
* 2.设置wrap_content和math_content的效果也是一样的
*/
public class CircleView extends View {
private int myColor = Color.RED;
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public CircleView(Context context) {
super(context);
init();
}
public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
/**
* 找到自己在values中自定义的attrs属性。
* 并对属性进行设置颜色值
*/
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
myColor = a.getColor(R.styleable.CircleView_circle_color,Color.RED);
a.recycle();
init();
}
private void init() {
mPaint.setColor(myColor);
}
/**
* 设置默认的高度和宽度
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST && heightMeasureSpec == MeasureSpec.AT_MOST){
setMeasuredDimension(200,200);
}else if (widthSpecMode == MeasureSpec.AT_MOST){
setMeasuredDimension(200,heightSpecSize);
}else if (heightSpecMode == MeasureSpec.AT_MOST){
setMeasuredDimension(widthSpecSize,200);
}
}
/**
* 实现padding的效果
* @param canvas
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
*获取不同的padding值可以设置一定的padding属性效果
* 此时的warp_content和padding使用就有效果了
*/
final int paddingLeft = getPaddingLeft();
final int paddingRight = getPaddingRight();
final int paddingTop = getPaddingTop();
final int paddingBottom = getPaddingBottom();
int width = getWidth() - paddingLeft -paddingRight;
int height = getHeight() - paddingTop - paddingBottom;
int radius = Math.min(width,height)/2;
canvas.drawCircle(paddingLeft + width/2,paddingTop + height/2,radius,mPaint);
}
}
2.布局代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:background="#ffffff"
android:orientation="vertical"
android:layout_height="match_parent">
<!--绘画一个圆形图片-->
<com.zhjy.measureview.CircleView
android:layout_width="wrap_content"
android:background="#000000"
android:layout_margin="20dp"
android:padding="20dp"
app:circle_color="@color/colorAccent"
android:layout_height="100dp" />
</LinearLayout>