问题
I'm new in Android development and I'm trying to draw a line inside my yellow RelativeLayout from bottom left corner to top right corner.
I've added a layer-list - diagonal_line
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:top="300dp"
android:bottom="-300dp"
android:left="0dp"
android:right="-300dp">
<rotate
android:fromDegrees="-10"
android:pivotX="0%"
android:pivotY="100%" >
<shape
android:shape="line"
android:top="1dip" >
<stroke
android:width="1dip"
android:color="#000" />
</shape>
</rotate>
</item>
then to styles
<style name="diagonalStyle">
<item name="android:background">@drawable/diagonal_line</item>
</style>
then added it to my RelativeLayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
style="@style/diagonalStyle"
android:background="#FFDC7F">
My problem is that if I add the color the line is not showing and without color the line appears but is not in the correct position. Perhaps this question is a duplicate but please be gentle, I don't know what am I doing wrong.
回答1:
You should use VectorDrawable path to draw line inside yellow RelativeLayout from bottom left corner to top right corner. Your diagonal_line.xml should be like (assume line color is blue #0000FF and line width is 4):
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="64dp"
android:width="64dp"
android:viewportHeight="600"
android:viewportWidth="600" >
<path
android:name="diagonal_line"
android:strokeColor="#0000FF"
android:strokeWidth="4"
android:pathData="M600, 0 l-600, 600z" />
</vector>
(absolute dimensions not important, because vector will be rescaled for RelativeLayout size). Your styles.xml should include section
<style name="diagonalStyle">
<item name="android:background">@drawable/diagonal_line</item>
</style>
as you wrote, and in case you cannot use backgroundTint in your {your_layout}.xml file, you should set solid colored background (android:background="#FFDC7F") for your Relativelayout and put "dummy" View with diagonalStyle (style="@style/diagonalStyle") over it. Something like that:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFDC7F"
tools:context="{YOUR_CONTEXT}">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/diagonalStyle" />
</RelativeLayout>
As result, you should give something like that:
More path tutorial here.
来源:https://stackoverflow.com/questions/48281022/draw-diagonal-line-from-corner-to-corner-inside-relativelayout