项目设计图中有个虚线的设计,本来很简单,直接写一个Shape
就行。
代码:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke
android:width="1dp"
android:color="#fc8029"
android:dashGap="4dp"
android:dashWidth="15dp" />
</shape>
dashGap
是间隔的宽度,dashWidth
是横线的宽度
然而怎么调试都显示的仍旧是一条直线,后来网上查到跟硬件加速有关。然后查了查文档,文档。才发现,自定义的view渲染的时候,如果开启硬件加速,可能会渲染出错,需要关闭。
However, because hardware acceleration is not supported for all of the 2D drawing operations, turning it on might affect some of your custom views or drawing calls.
而关闭硬件加速有几个层级
Application
在Android manifest
文件中的<application>
标签下,添加以下语句,关闭整个application
的硬件加速
<application android:hardwareAccelerated="true" ...>
页面复杂的时候,不开启硬件加速渲染会有卡顿的感觉,不建议用
Activity
可对单个的Activity
关闭硬件加速
<application android:hardwareAccelerated="true">
<activity ... />
<activity android:hardwareAccelerated="false" />
</application>
Window
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
文档里有注意:
Note: You currently cannot disable hardware acceleration at the window level.
在window
级别,可以打开但不能关闭硬件加速。
View
在指定的view
上关闭硬件加速
myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
文档里有注意:
Note: You currently cannot enable hardware acceleration at the view level. View layers have other functions besides disabling hardware acceleration.
在view
级别,只能关闭不能打开,因为还需要有其他的设置
直接在xml文件中关闭该view 的硬件加速
添加android:layerType="software"
代码:
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="20dp"
android:background="@drawable/line_stop"
android:layerType="software" />
定义的layout_height
要比shape
中的高1dp,否则不显示。
判断是否启用了硬件加速?
1.View.isHardwareAccelerated()
,返回该view是否启用了硬件加速
2.Canvas.isHardwareAccelerated()
,返回canvas是否启用了
搞了一大圈,最后身兼数职的美工告诉我直接用实线就行,他弄错了而已(๑´ㅂ`๑)