Android自定义View,画一个好看带延长线的饼状图

TI SmartRF TrxEB评估板:射频开发、低功耗测量与原型设计实战指南 在嵌入式系统与物联网开发中,无线通信模块的评估与原型搭建是核心环节。其原理在于通过标准化的硬件接口与软件工具,对射频芯片的收发性能、功耗及协议栈进行快速验证。这项技术的价值在于能大幅缩短从芯片选型到产品原型的开发周期,降低硬件设计风险,广泛应用于智能家居、工业传感、资产追踪等低功耗无线节点场景。本文聚焦于TI SmartRF TrxEB评估板,深入解析其双MCU架构、三种核心工作模式(SmartRF、UART、Disabled)以及精准的电流测量方法,并结合低功耗测量和射频性能评估等热词,提供从快速射频测试 阅读详情

前言

在Android中,图表的实现是比较麻烦的,基本只能通过自定义View来实现。目前Github上有一些集成度高功能性强的三方库,比如MPAndroidChart等。但三方库虽然强大,定制性总是有限的,在项目中为了达成一些特别需求,就要靠我们自己去画啦。虽然费点时间,不过计算各种绘制点的位置的过程还是很有趣的。我个人对于自定义View这部分只是小有了解,所以大家如果对本文中的代码有什么改进意见,欢迎在评论区或者我的github项目上提issues出来啦~

绘制思路

先来看一下,在项目中设计师给到我要实现的样子:

无视设计师画图时数字和占比不符的偷懒,可以看到这是一个普通的饼状图加上延长线、文字描述和一些圈圈点点,那么整理一下大致的绘制思路,我的想法是:

1.绘制饼状图
确定饼状图所处的正方形区域,找出圆点
通过drawArc绘制扇区,绘制出饼图的各个部分
中间画一个圆,让饼图变为只有外面一圈

2.绘制饼图外的点、圈、线、字
点的角度处于每个圆弧的半分处,通过正余弦算出点的位置
以点为圆心画圈
按照四个象限,不同象限以不同角度从圈边延长出线
以线的终点对齐加上字

2.给自定义View增加空间,以避免延长线和字显示不全
主要用到了数学中坐标系象限的概念和正余弦的算法,看着有点绕,确实也是挺绕的,接下来分步骤详细描述吧。
绘制饼图
首先我们需要存储各个饼图所需要的属性:

public class PieEntry {
    //颜色
    private int color;
    //比分比
    private float percentage;
    //条目名
    private String label;
    //扇区起始角度
    private float currentStartAngle;
    //扇区总角度
    private float sweepAngle;
    //省略get&set
}

在绘制饼图中,我们只需要颜色、百分比就够了,其他的在后面的步骤才会用到。
确定圆点
在布局文件中,我们将自定义View的宽度设为match_paren,高度设为300dp,并添加一个浅色作为背景色。

饼图作为一个圆,那么在绘制这个圆前,我们先找出圆心的位置,并将其作为整个View的原点,即坐标(0,0)的位置。

在这里我向View中添加了坐标轴和原点的辅助线,作为指示用。

 

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    //获取实际View的宽高
    mTotalWidth = w - getPaddingStart() - getPaddingEnd();
    mTotalHeight = h - getPaddingTop() - getPaddingBottom();
    //绘制饼图所处的正方形RectF
    initRectF();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //将坐标中心设到View的中心
    canvas.translate(mTotalWidth / 2, mTotalHeight / 2);
    //draw...
}

创建正方形RectF,确定饼图半径
在确定圆心并将其设为坐标原点后,创建一个边长等于View短边长的正方形RectF:

private void initRectF() {
    float shortSideLength;
    //取短边 作为饼图所在正方形的边长
    shortSideLength = (mTotalHeight < mTotalWidth) ? mTotalHeight : mTotalWidth;
    //除以2即为饼图的半径
    mRadius = shortSideLength / 2;
    //设置RectF的坐标
    mRectF = new RectF(-mRadius, -mRadius, mRadius, mRadius);
}

 

设置paint颜色为红色,将这个Rect通过canvas.drawRect(mRectF, mPaint);在View中绘制出来,可以看到其边长是和高度一致的:

那么为什么需要创建这个正方形RectF呢?因为在接下来的饼图绘制中会用到。可以简单理解为这个正方形就是饼图的外轮廓所处的范围,也就是长方形的边长即是饼图的直径。

Android自定义View,画一个好看带延长线的饼状图,android移动应用开发教程清华大学 那么为什么需要创建这个正方形RectF呢?因为在接下来的饼图绘制中会用到。可以简单理解为这个正方形就是饼图的外轮廓所处的范围,也就是长方形的边长即是饼图的直径。 绘制扇形 虽然饼图是一个圆,但这是相对于其整体而言。在一个饼图中,不同的类目占比不同,将饼图分割成了多个扇形,所以我们实际上是要绘制扇形。在Android自定义View中,对应的方法是 drawArc,所需要的参数包括: 图片引用自:刘某人程序员——Android绘图机制(二) 这里受限于篇幅不能详细介绍,不了解的同学一定要先去网上看一下相关 阅读详情

相关推荐

Android 自定义View画圆环统计图

public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, @Nullable AttributeSet attrs) { super(context, attrs...

try_zp_catch的博客 1001

LangChain开发避坑指南:为什么Pylance总提示‘无法解析导入‘?实测7种修复方案

本文深入解析了在VS Code中使用LangChain开发时,Pylance频繁提示‘无法解析导入’的根本原因——Python解释器与语言服务器的环境路径不一致。文章提供了从基础排查到深度配置的7种实测修复方案,包括切换解释器、配置extraPaths、使用pyrightconfig.json等,旨在帮助开发者彻底解决此问题,提升AI应用开发效率。

weixin_28826521的博客 444

基于多物理参数数据融合和先进人工智能算法的锂电池热失控监测传感器

基于多物理参数数据融合和先进人工智能算法的锂电池热失控监测传感器是多种方案中的优选项!是一种快速、准确、可靠、应用广泛的传感方案!可有效监测锂离子电池热失控风险,保障化学能储能电站安全!

chicheng_danxin的博客 2411

YOLO 系列专栏(二十九)YOLO26 × StarNet 轻量化涨点方案(CVPR 2024)轻量化、主干改进篇 | 星星卷积虽小,却蕴藏着巨大的高效潜力

StarNet 出自 CVPR 2024 轻量化主干网络工作,核心创新是,依靠逐元素乘法实现高阶特征融合,在几乎不增加参数量与 FLOPs 的前提下,大幅提升特征表达能力,天然适合等多任务统一建模。本文将 StarNet 完整替换 YOLO26 原有主干,保留 YOLO26 无 NMS 检测头与轻量化结构,实现,并提供。

qq_36130719的博客 410

ESP32与BH1750光照传感器结合使用的Web服务器案例

请注意,为了使代码正常工作,你需要将代码中的"你的WiFi网络名称"和"你的WiFi网络密码"替换为你自己的WiFi网络凭据。在代码中,我们首先导入了所需的库文件,包括Wire库用于I2C通信,BH1750库用于与光照传感器通信,WiFi库和WebServer库用于创建Web服务器。接下来,我们将编写一个Arduino代码来控制ESP32与BH1750的通信,并将读取到的光照强度值显示在Web服务器上。函数用于处理根路径的请求,其中我们读取光照传感器的值,并将其显示在返回的HTML页面中。

server_api196的博客 617

Open3D (C++) 点云边界提取【2025最新版】

Compute the boundary points of a point cloud.The implementation is inspired by the PCL implementation. Reference:https://pointclouds.org/documentation/classpcl_1_1_boundary_estimation.html

点云侠的博客 871

RT-DETR改进策略【卷积层】| CGblock 内容引导网络 利用不同层次信息,提高多类别分类能力 (含二次创新)

本文记录的是利用中的模块优化的目标检测网络模型。通过局部特征提取器、周围环境提取器、联合特征提取器和全局环境提取器来提取局部特征、周围环境和全局环境信息,充分利用不同层次的信息。本文将其应用到中,并进行二次创新,使网络能够更好的处理多类别目标的分类能力。CGNet: A Light-Weight Context Guided Network for Semantic Segmentation1️⃣ 首先通过局部特征提取器floc(∗)floc(*)floc(∗)和周围环境提取器fsur(∗)f_{sur }

Limiiiing的博客 1349

SDA 还是 SDI:SAP HANA 数据虚拟化与数据集成的取舍、组合与实战

结论先放在前面:SDA 面向数据虚拟化与联邦查询,强调不落地、不复制、按需实时访问;SDI 面向数据集成与复制,强调抽取、转换、装载与近实时增量同步。两者共享 Remote Source 与 Adapter 的理念,但侧重点与运行时组件明显不同。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 583

基于深度学习的灰度图像气泡群识别与优化

灰度图像气泡群深度学习识别优化研究 本研究针对MATLAB实现的深度学习气泡群识别系统在从1445个点到4992个点扩展时出现的精度不稳定问题,提出了一套完整的解决方案。文章首先分析了问题根源,包括数据复杂度增加、类别不平衡、网络容量不足等因素,然后系统性地提出了数据预处理增强、网络架构优化、训练策略调整和后处理算法改进等优化措施。通过改进的U-Net架构、自适应直方图均衡化等技术创新,有效提升了模型在大规模气泡群图像上的识别精度和稳定性,为化工、生物医学等领域的灰度图像分析提供了可靠的技术支持。

max500600的博客 411

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: App相互唤醒的几种方式
下一篇: Android上手机软件调用外部地图软件
动脑学院[David]
博客等级 码龄8年 44粉丝 31原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值