簡體   English   中英

Android 裁剪背景

[英]Android crop background

我有一個LinearLayout ,其寬度設置為fill_parent ,高度設置為wrap_content 現在我想給它一個來自 png 文件的背景,但是以傳統方式執行它會導致LinearLayout調整大小以顯示整個背景而不是裁剪附加部分。

如何設置LinearLayout的背景使其不會調整大小?

謝謝

似乎只有使用ImageView並相應地設置scaleType參數才能實現這樣的事情。 一個快速的解決方法是使用FrameLayout並將ImageView放在另一個具有透明背景的布局下。

代碼:

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/background" />

</FrameLayout>

背景位圖的默認行為是完全填充容器並在需要時增加容器的水平和垂直大小。 解決方案是創建一個可繪制的 bitmap 資源並更改重力。

檢查以下鏈接並查找可能的重力值。 然后,您的視圖應該只引用可繪制資源,您應該沒問題。

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

我通過繼承LinearLayout並覆蓋onMeasure(int,int)回調解決了這個問題,然后更新布局 XML 以使用我的新布局類型。 我不能發布確切的代碼,但我所做的是調用super.onMeasure(int,int)實現並檢查測量的高度是否返回為我的背景圖像的確切高度。 如果是這樣,我會獲取所有子視圖的測量高度,然后計算一個新的高度值並將其傳遞給setMeasuredDimension(int,int)

將此代碼放在 xml 活動中,例如 activity_main.xml

<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/image" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM