2014-10-11 111 views
12

我想绘制像这样的自定义形状 - Custom ShapeAndroid:绘制自定义形状

一种选择是在Photoshop中单独制作每个形状,然后在编码中使用它,但是我想知道是否可以使用xml绘制它?

我该如何画这样的形状?不要指望完整的代码,只是给我想法或指向正确的方向。

回答

32

试试下面的形状绘制的xml:

<?xml version="1.0" encoding="UTF-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > 

<!-- Colored rectangle--> 
<item> 
    <shape android:shape="rectangle"> 
     <size 
      android:width="100dp" 
      android:height="40dp" /> 
     <solid android:color="#FAD55C" /> 
    </shape> 
</item> 

<!-- This rectangle for the left side --> 
<!-- Its color should be the same as layout's --> 
<item 
    android:right="90dp" 
    android:left="-30dp"> 
    <rotate 
     android:fromDegrees="45"> 
     <shape android:shape="rectangle"> 
      <solid android:color="#ffffff" /> 
     </shape> 
    </rotate> 
</item> 

<!-- These rectangles for the right side --> 
<!-- Their color should be the same as layout's --> 
<item 
    android:top="-40dp" 
    android:bottom="63dp" 
    android:right="-25dp"> 
    <rotate 
     android:fromDegrees="45"> 
     <shape android:shape="rectangle"> 
      <solid android:color="#ffffff" /> 
     </shape> 
    </rotate> 
</item> 

<item 
    android:top="63dp" 
    android:bottom="-40dp" 
    android:right="-25dp"> 
    <rotate 
     android:fromDegrees="-45"> 
     <shape android:shape="rectangle"> 
      <solid android:color="#ffffff" /> 
     </shape> 
    </rotate> 
</item> 
</layer-list> 

这就是它看起来像一个白色背景:

enter image description here

这里是Shape Drawables更多信息。

编辑:

下面是它是如何做一个小的解释。

  1. 我们放置一个100 x 40 dp大小的黄色矩形。从现在开始,这个矩形可以被看作是其余形状的容器。容器的边界被认为是我们将要放置在容器内的形状边界的起源。即,设定形状的size标签的top, bottom, right and left属性是指从该形状的边界到所述容器(黄色矩形)的top, bottom, right and left边缘的距离。

例如,如果我们想放置一个较小的矩形的黄色一个的内部从每个黄色矩形的边缘的间隙10dp我们会设置top, bottom, right and left属性等于10dp为新的(内部)的矩形。

  1. 为了实现黄色矩形右侧的箭头状形状,我们使用了两个适当地向右移动并旋转的白色矩形。注意,size标签属性的值可以是负值,这意味着形状的相应边出现在容器的外部。在前面的示例中,如果将left属性设置为100 dp或更高,则内部矩形将不会显示,因为它将位于黄色右边界的后面。

关于旋转,顺时针旋转为正值,否则逆时针旋转。

  1. 对于左侧形状,只需使用一个移动到左侧(部分位于容器外部)和45度旋转的矩形即可。

希望这并没有让你感到困惑。

+1

这是非常好的,今天学到了一些有创意的东西,谢谢你 – 2018-02-06 08:02:58