当需要动态的绘制二维图形时,可以用 ShapeDrawable 来完成。可以通过编程的方式绘制初始形状。
ShapeDrawable 是属于 Drawable 的扩展。ShapeDrawable 的构造器如果为空,则默认的为矩形。
效果如下:
MyDrawableView.java :
package com.scxh.shapedrawabletest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by antimge on 2015/12/21.
* 如果只是要随意的绘制一个图形,可省略测量等方法
*/
public class MyDrawableView extends View {
private ShapeDrawable mDrawable;
// 定义图形的长宽(如果图形为 OvalShape ,相等则为圆形,不相等则为椭圆)
private final int WIDTH = 160, HEIGHT = 80;
public MyDrawableView(Context context) {
this(context, null);
}
public MyDrawableView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyDrawableView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// 设置图形,如果该构造方法为空,则默认显示的是矩形
mDrawable = new ShapeDrawable(new OvalShape());
// 修改默认颜色(默认色为黑色)
mDrawable.getPaint().setColor(0xff74AC23);
// 设置透明度(半透明)
mDrawable.setAlpha(128);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width, height;
// 确定内容的理想大小,无约束
int cWidth = 100;
int mHeight = 100;
width = getHowToGetWH(widthMeasureSpec, cWidth);
height = getHowToGetWH(heightMeasureSpec, mHeight);
// 使用测量必须调用该方法
setMeasuredDimension(width, height);
}
/**
* 测量宽度和高度的方法
*/
private int getHowToGetWH(int measureSpec, int mSize) {
int specSize = MeasureSpec.getSize(measureSpec);
switch (MeasureSpec.getMode(measureSpec)) {
case MeasureSpec.AT_MOST:
return Math.min(specSize, mSize);
case MeasureSpec.UNSPECIFIED:
return mSize;
case MeasureSpec.EXACTLY:
return specSize;
default:
return 0;
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// 如果有变化,则复位参数
if (w != oldw || h != oldh) {
int x = w / 2;
int y = h / 2;
// 设置边界,否则定义的形状将不会绘制
// 该方法中的 4 个参数都要和定义的 x, y 相关联,该 4 个参数依次为左,上, 右, 下
// 此处居中
mDrawable.setBounds(x - WIDTH, y - HEIGHT, x + WIDTH, y + HEIGHT);
}
}
/**
* ShapeDrawable 自己的方法
*/
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
}
content_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.scxh.shapedrawabletest.MainActivity"
tools:showIn="@layout/activity_main">
<com.scxh.shapedrawabletest.MyDrawableView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>