Android自定义View绘制几何图形

时间:2023-02-06 22:05:09

画的矩形:

Android自定义View绘制几何图形

自定义View中

package android.zhh.com.mycanvas;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

/**
* Created by Administrator on 2016/4/1.
*/
public class MyView extends View {

// 一般会重写3个构造方法
public MyView(Context context) {
super(context);

}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);

}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

/**
* 视图的绘制事件
* 自动调用
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
// 手机屏幕的宽度
int width = wm.getDefaultDisplay().getWidth();
// 手机屏幕的高度
int height = wm.getDefaultDisplay().getHeight();

Paint paint = new Paint();
paint.setColor(Color.parseColor("#663399"));
// 画布
// 显示的字是x轴10,y轴10,paint画笔
// 参数:相对坐标,切线,左,上,右,下,画笔
// 画矩形
// canvas.drawRect(100f,0f,width,500f,paint);
// 画文本
// canvas.drawText("画圆:", 500, 500, paint);// 画文本
// 画大圆
// canvas.drawCircle(500,500,300,paint);//大圆
// 画线
// canvas.drawLine(0f,300f,width,300f,paint);
// 画斜线
// canvas.drawLine(110, 40, 190, 80, paint);

//画笑脸弧线
Paint p = new Paint();
// p.setStyle(Paint.Style.STROKE);//设置空心
//
// RectF oval1 = new RectF(150, 20, 180, 40);
//
// canvas.drawArc(oval1, 180, 180, false, p);//小弧形
//
// oval1.set(190, 20, 220, 40);
//
// canvas.drawArc(oval1, 180, 180, false, p);//小弧形
//
// oval1.set(160, 30, 210, 60);
//
// canvas.drawArc(oval1, 0, 180, false, p);//小弧形


// 画矩形
p.setColor(Color.GRAY);// 设置灰色
p.setStyle(Paint.Style.FILL);//设置填满
canvas.drawRect(100f, 100f, 1000f, 500f, p);// 正方形
Log.e("111","width>>>"+width);




}
}

布局文件中引用:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<android.zhh.com.mycanvas.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</android.zhh.com.mycanvas.MyView>

</LinearLayout>
源码下载:http://download.csdn.net/detail/zhaihaohao1/9792733

参考文章:http://blog.csdn.net/qq_34308476/article/details/51645859