ef2*_*011 98 android android-layout
我找到了这个伟大的主题,描述了如何"吃蛋糕并拥有它",即使用图像Button代替ImageButton(不允许SetText(),调整大小等).
这是通过使用View属性实现的:
android:background="@drawable/bgimage"
Run Code Online (Sandbox Code Playgroud)
唯一的问题是它会拉伸图像以适应按钮大小.
没有硬编码固定按钮大小(以像素为单位!),有没有办法告诉Android 不要拉伸背景图像并裁剪或填充它?
小智 259
您可以创建一个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>
Run Code Online (Sandbox Code Playgroud)
您可以使用许多选项来自定义图像的渲染
http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap
小智 29
如果您不希望它伸展,您应该使用ImageView.背景图像将始终拉伸以适合视图.您需要将其设置为Drawable以强制图像方面到对象.
否则,如果你坚持使用Button的想法,那么你需要在按钮中强制缩放以防止图像拉伸.
比如你的
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);
}
Run Code Online (Sandbox Code Playgroud)
Adi*_*lik 25
只需使用ImageButton而不是Button修复问题.
<ImageButton android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/bgimage" />
Run Code Online (Sandbox Code Playgroud)
你可以设置
android:background="@null"
Run Code Online (Sandbox Code Playgroud)
如果需要,删除按钮背景.
快速解决 !!:-)
Gun*_*ein 10
我在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>
Run Code Online (Sandbox Code Playgroud)
使用Android Studio SDK工具中包含的draw9patch ...。您可以定义图像的可拉伸区域。重要部分受到约束,图像看起来并没有全部变形。这里有一个关于dra9patch的好演示
使用draw9patch将现有的splash.png更改为new_splash.9.png,将new_splash.9.png拖动到drawable-hdpi项目文件夹中,确保AndroidManifest和styles.xml如下所示正确:
AndroidManifest.xml:
<application
...
android:theme="@style/splashScreenStyle"
>
Run Code Online (Sandbox Code Playgroud)
styles.xml:
<style name="splashScreenStyle" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowBackground">@drawable/new_splash</item>
</style>
Run Code Online (Sandbox Code Playgroud)