如何使来自多个图像的绘制?多个、图像

2023-09-06 00:16:23 作者:弦已断ぃ人终散

我有3个9补丁PNG的其中一起组成了背景按钮(左边,中间,右边)。我想这三个图像组合在一起,我可以为背景以XML按钮,沿线的一些指定绘制:

I have three 9-patch PNG's which together make up the background for a button (left side, middle, right side). I would like to combine these three images together in a drawable which I can specify as the background for a button in XML, something along the lines of:

RES /绘制/ button_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<nine-patch xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/button_left_side" />

<nine-patch android:src="@drawable/button_middle" />

<nine-patch android:src="@drawable/button_right_side" />

RES /布局/ main.xml中:

<button android:background="@drawable/button_background" />

这可能吗?

推荐答案

在一些试验和错误,我是能够解决的问题以令人满意的方式。我只是实现了一个图层,绘制列表如下:

After some trial-and-error, I was able to solve the problem in a satisfactory way. I simply implemented a Layer-List drawable as follows:

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/btn_left" android:left="0px" />
    <item android:drawable="@drawable/btn_middle" 
        android:left="26px" android:right="26px" />
    <item android:drawable="@drawable/btn_right" android:right="0px" />
</layer-list>

26px 值是两个按钮侧图像的像素宽度。

Where the 26px values are the width of the two button side images in pixels.

要使用此绘制,只需调用它像任何其他绘制:

To use this drawable, simply call it like any other drawable:

<bitmap android:src="@drawable/button_background" />

这工作完全,你会怎么指望它,中间扩大为正常,以适应所需的宽度,以及所有三个图像扩大,以适应所需的高度。我希望其他人可以从中受益!

This works exactly how you would expect it to, with the middle expanding as normal to fit the desired width, and all three images expanding to fit the desired height. I hope others can benefit from this!