IT박스

늘어나지 않는 android : background를 구현하는 방법은 무엇입니까?

itboxs 2020. 8. 21. 07:28
반응형

늘어나지 않는 android : background를 구현하는 방법은 무엇입니까?


나는 "케이크를 먹고 그것도 가지고있는"방법을 설명하는 훌륭한 스레드발견했다 . 즉, Button대신에 이미지를 사용한다 ImageButton(허용하지 않는 것 SetText(), 크기 조정 등).

이는 View 속성을 사용하여 수행됩니다.

android:background="@drawable/bgimage"

이것의 유일한 문제는 버튼 크기에 맞게 이미지를 늘린다는 것입니다.

고정 된 버튼 크기 (픽셀 단위!)를 하드 코딩 하지 않고 Android 에 배경 이미지를 전혀 늘리지 않고 자르거나 패딩하도록 지시하는 방법 이 있습니까?


확장하지 않으려면 ImageView를 사용해야합니다 . 배경 이미지는 항상 뷰에 맞게 늘어납니다. 이미지 측면을 개체에 강제로 적용하려면 Drawable로 설정해야합니다.

그렇지 않고 버튼 아이디어를 고수한다면 이미지가 늘어나는 것을 방지하기 위해 버튼의 크기 조절을 강제해야합니다.

당신의

OnCreate(Bundle bundle) {
  //set content layout, etc up here

  //now adjust button sizes
  Button B = (Button) findViewById(R.id.somebutton);
  int someDimension = 50; //50pixels
  B.setWidth(someDimension);
  B.setHeight(someDimension);
}

xml 비트 맵을 작성하여보기의 배경으로 사용할 수 있습니다. 스트레칭을 방지하기 위해 android:gravity속성 을 지정할 수 있습니다 .

예를 들면 :

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

이미지 렌더링을 사용자 정의하는 데 사용할 수있는 많은 옵션이 있습니다.

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


ImageButton대신 사용 Button하면 문제가 해결됩니다.

<ImageButton android:layout_width="30dp"
             android:layout_height="30dp"
             android:src="@drawable/bgimage" />

그리고 당신은 설정할 수 있습니다

android:background="@null"

원하는 경우 버튼 배경을 제거합니다.

빠른 수정 !! :-)


일반 레이아웃과 오버레이되는 RelativeLayout에서 ImageView를 사용하고 있습니다. 코드가 필요하지 않습니다. 화면의 전체 높이 (또는 사용하는 다른 레이아웃)에 맞게 이미지 크기를 조정 한 다음 너비에 맞게 그림을 왼쪽과 오른쪽으로 자릅니다. 제 경우에는 사용자가 화면을 돌리면 화면이 너무 작아 질 수 있습니다. 따라서 너무 작 으면 이미지 너비가 늘어나도록하는 match_parent를 사용합니다.

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

    <ImageView
        android:id="@+id/main_backgroundImage"
        android:layout_width="match_parent"
        //comment: Stretches picture in the width if too small. Use "wrap_content" does not stretch, but leaves space

        android:layout_height="match_parent"
        //in my case I always want the height filled

        android:layout_alignParentTop="true"
        android:scaleType="centerCrop"
        //will crop picture left and right, so it fits in height and keeps aspect ratio

        android:contentDescription="@string/image"
        android:src="@drawable/your_image" />

    <LinearLayout
        android:id="@+id/main_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

저도 같은 문제가있었습니다. 원본 사진 대신 9 패치 이미지 (.9.png) 만 사용해야합니다.

서지


Android Studio의 SDK 도구에 포함 된 draw9patch ...를 사용하십시오 . 이미지의 확장 가능한 영역을 정의 할 수 있습니다. 중요한 부분은 제한되어 있으며 이미지가 모두 뒤 틀리지는 않습니다. dra9patch에 대한 좋은 데모가 여기 있습니다.

Use draw9patch to change your existing splash.png into new_splash.9.png, drag new_splash.9.png into the drawable-hdpi project folder ensure the AndroidManifest and styles.xml are proper as below:

AndroidManifest.xml:

<application
...
        android:theme="@style/splashScreenStyle"
>

styles.xml:

<style name="splashScreenStyle" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowBackground">@drawable/new_splash</item>
</style>

I had a background image, not big in size, but with weird dimensions - therefore the stretching and bad performance. I made a method with parameters Context, a View and a drawable ID(int) that will match the device screen size. Use this in e.g a Fragments onCreateView to set the background.

public void setBackground(Context context, View view, int drawableId){
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),drawableId);

    bitmap = Bitmap.createScaledBitmap(bitmap, Resources.getSystem().
             getDisplayMetrics().widthPixels,
             Resources.getSystem().getDisplayMetrics().heightPixels,
             true);

    BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), 
                                    bitmap);

    view.setBackground(bitmapDrawable);
}

Here's a version of Santosh's answer for programmatically-created buttons, without the need for a separate XML configuration:

Button button = new Button(getContext());
Bitmap backgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_button);
BitmapDrawable backgroundDrawable = new BitmapDrawable(getResources(), backgroundBitmap);
backgroundDrawable.setGravity(Gravity.CENTER); // also LEFT, CENTER_VERTICAL, etc.
backgroundDrawable.setColorFilter(new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP));
button.setBackground(backgroundDrawable);

I included the ColorFilter line since that works a little differently from buttons with a normal background image.


You can use a FrameLayout with an ImageView as the first child, then your normal layout as the second child:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

  <LinearLayout
        android:id="@+id/your_actual_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

  </LinearLayout>

</FrameLayout>

The key is to set the drawable as the image of the button, not as a background. Like this:

rb.setButtonDrawable(R.drawable.whatever_drawable);

One can use a plain ImageView in his xml and make it clickable (android:clickable="true")? You only have to use as src an image that has been shaped like a button i.e round corners.

참고URL : https://stackoverflow.com/questions/5902230/how-to-implement-an-androidbackground-that-doesnt-stretch

반응형