自定义View创建简易柱状图

效果如下:
在这里插入图片描述

创建Activity,继承View:

package com.example.day_02;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class OneActivity extends View {
Paint mPaint;
public OneActivity(Context context) {
super(context);
init();
}
public OneActivity(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
//创建、设置画笔
private void init() {
mPaint=new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setStrokeWidth(10);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(20,20,20,350,mPaint);
mPaint.setColor(Color.RED);
canvas.drawLine(20,350,500,350,mPaint);
//设置矩形
Rect rect=new Rect();
rect.top=40;
rect.bottom=350;
rect.left=50;
rect.right=100;
//设置矩形的颜色
mPaint.setColor(Color.DKGRAY);
canvas.drawRect(rect,mPaint);

    Rect rect2=new Rect();
    rect2.top=90;
    rect2.bottom=350;
    rect2.left=140;
    rect2.right=180;
    //设置矩形的颜色
    mPaint.setColor(Color.GREEN);
    canvas.drawRect(rect2,mPaint);

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
}

}

XML中:

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout 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”
tools:context=".MainActivity">

<com.example.day_02.OneActivity
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” />

</android.support.constraint.ConstraintLayout>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值