2010-12-01 73 views
21

我設置具有以下可繪製背景的LinearLayout:Android的XML圓潤剪切的邊角

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <corners android:radius="10dp" /> 
    <solid android:color="#CCFFFFFF"/> 
</shape> 

我遇到的問題是在的LinearLayout內我有坐在它的底部另一個LinearLayout中元素的父。由於沒有圓角,它的拐角延伸過父母的左下角和右下角。

對孩子的LinearLayout的背景繪製如下:

<?xml version="1.0" encoding="utf-8"?> 
<bitmap 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:src="@drawable/pedometer_stats_background" 
    android:tileMode="repeat" 
/> 

的問題是這樣的:http://kttns.org/hn2zm設備上的非剪裁更爲明顯。

什麼是完成剪裁的最佳方法?

+2

我猜它會被巧妙地使用填充和邊距來解決 – schwiz 2010-12-01 19:23:15

回答

6

你的描述聽起來就好像什麼:

<LinearLayout android:shape="rounded"> 
    <LinearLayout android:background="@drawable/pedometer_stats_background"> 
    </LinearLayout> 
</LinearLayout> 

和內部佈局是推動圓角之外,因爲它不是圓的。你必須圍繞你的位圖的角落。如果你有一個重複的位圖,你會想要定義一個九個補丁的drawable。圓角然後定義可擴展的圖形部分。

http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

這會是很好,如果我們可以只添加一個位圖的形狀繪製並有被應用爲皮膚上的任何形狀,我們正在繪製。而且,我敢打賭,如果您知道自己在做什麼,可以創建一個繪製位圖的Shape子類,但不幸的是,這並不包含在Android中。

+0

感謝你們,我試圖在沒有定製位圖的情況下離開。不能相信你不能阻止孩子流血。 – sgarman 2011-01-17 02:21:33

+0

好吧,你可以阻止它們,但它不是開箱即用的。用一點代碼和獨創性,你就可以創造出這樣的東西。 – chubbsondubs 2012-11-12 14:26:16

26

我需要iPhone風格的圓形佈局,背後有灰色背景。 (嘆息 - 總是複製iPhone)

我很沮喪,我無法找到掩蓋佈局的方法。這裏的大多數答案都表示使用背景圖片,但這不是我所需要的。


編輯:以前的答案使用FrameLayout和設置android:foreground繪製建議。這在視圖中引入了一些奇怪的填充。我更新了我的答案,使用更簡單的RelativeLayout技術。


訣竅是使用RelativeLayout;把你的佈局放在裏面。 在您的佈局下方,添加另一個ImageView,將其background設置爲合適的遮罩圖像幀。這將在您的其他佈局的頂部繪製。

在我的情況下,我做了一個9Patch文件,它是一個灰色的背景,用一個透明的圓角矩形切出來。

frame

這爲您的基礎佈局完美的面具。

XML代碼如下 - 這是一個正常的佈局XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="wrap_content" android:layout_width="fill_parent"> 

    <!-- this can be any layout that you want to mask --> 
    <LinearLayout android:id="@+id/mainLayout" 
     android:layout_height="wrap_content" 
     android:layout_width="fill_parent" android:orientation="vertical" 
     android:background="@android:color/white"> 

     <TextView android:layout_height="wrap_content" 
      android:layout_width="wrap_content" android:layout_gravity="center" 
      android:text="Random text..." /> 

    </LinearLayout> 

    <!-- FRAME TO MASK UNDERLYING VIEW --> 
    <ImageView android:layout_height="fill_parent" 
     android:layout_width="fill_parent" 
     android:background="@drawable/grey_frame" 
     android:layout_alignTop="@+id/mainLayout" 
     android:layout_alignBottom="@+id/mainLayout" /> 

</RelativeLayout> 

注意ImageView在底部,對準頂部&底部到主佈局,與掩蔽圖像組:

  • android:background="@drawable/grey_frame"

此引用我9Patch文件 - 和口罩的基本佈局通過在前景中繪製。

下面是一個顯示標準佈局上的灰色圓角的示例。

maskedLayout

HTH

3

API級21(傑利貝恩)加入View.setClipToOutline。從上Defining Shadows and Clipping Views Android文檔:

要夾的視圖到可拉伸的形狀,設置可繪製作爲視圖的背景...並調用View.setClipToOutline()方法。

我通過將父視圖的背景設置爲具有圓角半徑的GradientDrawable來測試此功能,並且將子視圖正確裁剪以匹配父項的相同圓角。