自定义View-绘图机制与处理技巧

2024-09-05 16:18

本文主要是介绍自定义View-绘图机制与处理技巧,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

转载自:http://blog.csdn.net/dakaniu/article/details/78846972
仅作学习之用

1 单位转换
由于各种屏幕密度不同,导致同样像素大小的长度,在不同密度的屏幕上显示的长度不同,如下是各个密度值中的换算公式,
在mdpi 中 1dp = 1px,
在hdpi 中 1dp = 1.5px,
在xhdpi 中 1dp = 2px,
在xxhdpi 中 1dp = 3px,
其直接的换算公式是: ldpi:mdpi:hdpi:xhdpi:xxhpi = 3:4:6:8:12
转换代码如下:

 /*** 根据手机的分辨率从 dp 的单位 转成为 px(像素) */public static int dip2px(Context context, float dpValue) {final float scale = context.getResources().getDisplayMetrics().density;return (int) (dpValue * scale + 0.5f);}/*** 根据手机的分辨率从 px(像素) 的单位 转成为 dp */public static int px2dip(Context context, float pxValue) {final float scale = context.getResources().getDisplayMetrics().density;return (int) (pxValue / scale + 0.5f);}/***  使用系统提供的TypedValue 进行转换*  */public static int dp2px(Context context,float dp){return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,context.getResources().getDisplayMetrics());}public static int px2dp(Context context,float px){return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,px,context.getResources().getDisplayMetrics());}

2 2D的绘图基础
系统通过提供Canvas对象来提供绘图的方法,比如

 // 画笔的属性以及对应功能 mPaint.setAlpha(8); //设置画笔的AlphamPaint.setStrokeWidth(5); //设置空心边框的宽度mPaint.setShader(new LinearGradient(0, 0, 400, 0, new int[]{Color.BLUE, 0x123321, Color.BLUE}, null, Shader.TileMode.CLAMP))mPaint.setTextSize(20);mPaint.setARGB(10,8,5,4); //设置颜色值,分别对应 透明度,红,绿,蓝的四个通道分量来决定像素点的颜色mPaint.setAntiAlias(true);//设置画笔的锯齿效果mPaint.setColor(Color.YELLOW);//设置画笔的颜色mPaint.setStyle(Paint.Style.STROKE);//设置画笔的风格:空心STROKE 或者实心FILLPath path = new Path(); //定义一条路径 path.moveTo(40,50);//移动到坐标 40 50path.lineTo(100,100);path.lineTo(100,50);path.lineTo(50,200);// 绘图的功能以及属性canvas.drawPath(path,mPaint);canvas.drawPosText("Hello",new float[]{100,100,//第一个字母的坐标 100,200,//第二个字母的坐标 ......100,300,100,400,100,500},mPaint);//在指定的位置绘制文本canvas.drawOval(100,200,400,300,mPaint);//绘制椭圆RectF rect = new RectF(50, 50, 200, 200);//定义一个矩形区域canvas.drawRoundRect(rect,30, //x轴的半径30, //y轴的半径mPaint);canvas.drawPoint(400,500,mPaint);//绘制点canvas.drawLine(200,300,500,600,mPaint);//绘制线canvas.drawArc(rect1, //弧线所使用的矩形区域大小0,  //开始角度90, //扫过的角度false, //是否使用中心mPaint);canvas.drawText("android",200,410,mPaint);//绘制文本canvas.drawRect(100,200,500,460,mPaint);//绘制矩形canvas.drawCircle(100,370,40,mPaint);//绘制圆形

3 XML绘图

3.1 Bitmap
在xml中的drawable/目录下可以创建Bitmap资源,举例,在drawable目录下创建bit_picture.xml并实现如下代码

<?xml version="1.0" encoding="utf-8"?>
<bitmapxmlns:android="http://schemas.android.com/apk/res/android"android:src="drawable/drawable_resource"android:antialias=["true" | "false"]android:dither=["true" | "false"]android:filter=["true" | "false"]android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |"fill_vertical" | "center_horizontal" | "fill_horizontal" |"center" | "fill" | "clip_vertical" | "clip_horizontal"]android:mipMap=["true" | "false"]android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

通过以上代码,可以直接将图片转换成Bitmap 直接使用

    //xml调用<ImageViewandroid:layout_width="100dp"android:layout_weight="1"android:layout_height="100dp"android:src="@drawable/bit_picture"/>//java中调用getResources().getDrawable(R.drawable.bit_picture);

3.2 Shape
通过shape可以在xml中绘制各种形状,举例 在res/drawable文件夹下,新建一个文件,命名为:shape_demo.xml 代码如下

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"> // |oval|line|ring<!-- shape = rectangle时使用,表示边角的圆弧半径 半径默认是1dp--><corners android:radius="9dp"android:topLeftRadius="5dp"android:topRightRadius="2dp"android:bottomLeftRadius="3dp"android:bottomRightRadius="4dp"/><!-- 实心填充 --><solid android:color="#00000000" /><!-- 描边:一般大小都是1dp --><strokeandroid:width="1dp"android:color="#ff000000"android:dashGap="15dp"android:dashWidth="40dp"/><!-- 四周留出来的空白,和xml文件中的pad效果一样,对内起作用 --><paddingandroid:bottom="30dp"android:left="20dp"android:right="30dp"android:top="20dp" /><!-- 指定大小 --><size android:height="400dp"android:width="400dp"/><!-- 背景颜色渐变 --><gradientandroid:angle="45"android:endColor="#ff00ff00"android:startColor="#ff0000ff"android:type="linear"android:useLevel="true"android:centerColor="#611111"/>
</shape>
调用方法同3.1

3.3 Layer
Layer主要是用来实现图层效果的,举例 在res/drawable文件夹下,新建一个文件,命名为:layer_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/arrow_right"/><item android:left="10.0dip"android:top="10.0dip"android:right="20.0dip"android:bottom="30.0dip"android:drawable="@drawable/arrow_right"/>
</layer-list>
调用方法同3.1

3.4 Selector
主要是实现静态绘图中的事件反馈,通过不同的事件设置不同的图像,在res/drawable文件夹下,新建一个文件,命名为:selector_demo.xml
举例1

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"><!-- 默认时背景图片--><item android:drawable="@drawable/red"/><!-- 没有焦点时背景图片--><item android:state_window_focused="false"android:drawable="@drawable/dark_yellow"/><!-- 非触摸模式下获得焦点并单击时背景图片--><item android:state_focused="true"android:state_pressed="true"android:drawable="@drawable/bule"/><!-- 触摸模式下获得焦点并单击时背景图片--><item android:state_focused="false"android:state_pressed="true"android:drawable="@drawable/black"/><!-- 选中时背景图片--><item android:state_selected="true"android:drawable="@drawable/dark_bule"/><!-- 获取焦点时背景图片--><item android:state_focused="true"android:drawable="@drawable/deep_yellow"/>
</selector>
// 调用方法同3.1

举例2 在Selector中使用shape来作为它的item

    <item android:state_pressed="true" ><shape android:shape="rectangle"><solid android:color="#224444"></solid><corners android:radius="5dp"/><padding android:right="10dp"android:top="10dp"android:left="10dp"android:bottom="10dp"/></shape></item><item ><shape android:shape="rectangle"><solid android:color="#FFFFFF"/><corners android:radius="5dp"/><padding android:bottom="10dp"android:top="10dp"android:left="10dp"android:right="10dp"/></shape></item>

4 绘图技巧

4.1 Canvas
作为绘图的直接对象, 以下几个方法非常好用

Canvas.save() // 将之前的所有已绘制的图像保存起来,后续操作就像在另一个图层上一样
Canvas.restore();//将save之后的绘图与sava之前的绘图合并起来
Canvas.translate();//平移坐标系
Canvas.rotate();//旋转坐标系
举例, 画一个仪表盘

 public CanvasView(Context context, @Nullable AttributeSet attrs) {super(context, attrs);mPaint = new Paint();mPaint.setStyle(Paint.Style.STROKE);mPaint.setAntiAlias(true);mPaint.setStrokeWidth(10);mWidth = 600;mHeight = 800;}@Overrideprotected void onDraw(Canvas canvas) {canvas.drawCircle(mWidth/2,mHeight/2,mWidth/2,mPaint);// 以mWidth/2,mHeight/2为圆心,以mWidth/2为半径,用mPaint画一个圆Log.i("niuniu ", " init  drawCircle ");mPaint.setStrokeWidth(8);for(int i = 0;i<24;i++){String value = String.valueOf(i);if(i==0 || i==6 || i == 12 ||i==18){mPaint.setStrokeWidth(6);mPaint.setTextSize(35);canvas.drawLine(mWidth/2,mHeight/2-mWidth/2,mWidth/2,mHeight/2-mWidth/2+60,mPaint);canvas.drawText(value,mWidth/2-mPaint.measureText(value)/2,mHeight/2-mWidth/2+110,mPaint);}else {mPaint.setStrokeWidth(4);mPaint.setTextSize(20);canvas.drawLine(mWidth/2,mHeight/2-mWidth/2,mWidth/2,mHeight/2-mWidth/2+30,mPaint);canvas.drawText(value,mWidth/2-mPaint.measureText(value)/2,mHeight/2-mWidth/2+60,mPaint);}canvas.rotate(15,mWidth/2,mHeight/2); //以mWidth/2,mHeight/2为圆心,将坐标系旋转15°}Paint paint1 = new Paint();paint1.setStrokeWidth(10);Paint paint2 = new Paint();paint2.setStrokeWidth(8);canvas.save(); // 保存画笔以及上面的圆环canvas.translate(mWidth/2,mHeight/2);//平移到圆心 已圆心为坐标起点 0,0canvas.drawLine(0,0,100,80,paint1);canvas.drawLine(0,0,100,120,paint2);canvas.restore(); // 将所画的的指针与sava之前的圆环合并起来super.onDraw(canvas);}

4.2 Layer图层
图层是基于栈的结构进行管理的.android通过saveLayer(),saveLayerAlpha()将一个图层入栈,利用restore(),restoreToCount()将图层出栈,入栈时,后面的操作都会发生在这个图层上,出栈时,会把图像绘制在上层的cavas上.
举例

        mPaint.setStyle(Paint.Style.FILL);mPaint.setColor(Color.BLUE);canvas.drawColor(Color.WHITE);canvas.drawCircle(150,150,100,mPaint);canvas.saveLayerAlpha(0,0,400,400,127,Canvas.ALL_SAVE_FLAG);//入栈,将后面所画的红色圆都发生在该图层上mPaint.setColor(Color.RED);canvas.drawCircle(200,200,100,mPaint);canvas.restore();//出栈,将前面所有的图像都绘制在该canvas上

这篇关于自定义View-绘图机制与处理技巧的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1139449

相关文章

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

快速修复一个Panic的Linux内核的技巧

《快速修复一个Panic的Linux内核的技巧》Linux系统中运行了不当的mkinitcpio操作导致内核文件不能正常工作,重启的时候,内核启动中止于Panic状态,该怎么解决这个问题呢?下面我们就... 感谢China编程(www.chinasem.cn)网友 鸢一雨音 的投稿写这篇文章是有原因的。为了配置完

Python ZIP文件操作技巧详解

《PythonZIP文件操作技巧详解》在数据处理和系统开发中,ZIP文件操作是开发者必须掌握的核心技能,Python标准库提供的zipfile模块以简洁的API和跨平台特性,成为处理ZIP文件的首选... 目录一、ZIP文件操作基础三板斧1.1 创建压缩包1.2 解压操作1.3 文件遍历与信息获取二、进阶技

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

Java Response返回值的最佳处理方案

《JavaResponse返回值的最佳处理方案》在开发Web应用程序时,我们经常需要通过HTTP请求从服务器获取响应数据,这些数据可以是JSON、XML、甚至是文件,本篇文章将详细解析Java中处理... 目录摘要概述核心问题:关键技术点:源码解析示例 1:使用HttpURLConnection获取Resp