Reputation: 3824
I have an image and I want to put it to full the screen fitting by width but cropping the top of the image, like this:
The red area is the image and the red one is the phone screen/parent layout. Of course, preserving aspect ratio. Is it possible in XML instead of programatically?
Upvotes: 1
Views: 4278
Reputation: 3824
Finally I solved my problem using a custom view:
public class ResizableImageView extends ImageView {
public ResizableImageView(Context context) {
super(context);
}
public ResizableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ResizableImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if (drawable != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int diw = drawable.getIntrinsicWidth();
if (diw > 0) {
int height = width * drawable.getIntrinsicHeight() / diw;
setMeasuredDimension(width, height);
return;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
And, the XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_margin="0dp"
android:padding="0dp"
tools:context=".SplashActivity" >
<com.xxx.widgets.ResizableImageView
android:id="@+id/imageSplash"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="0dp"
android:padding="0dp"
android:src="@drawable/img_splash"
tools:ignore="ContentDescription" />
</RelativeLayout>
Upvotes: 0
Reputation: 187
use
android:src="@drawable/img"
android:scaleType="fitEnd"
instead of
android:background
fitEnd retains aspect ratio as is written here
Upvotes: 1
Reputation: 3513
Ok for that You should Do This Steps:--
1). Make Linear Layout
2). apply the image as background
3). set the view at top to crop the background of layout.
i think you got what i am talking.
for example this is the xml:--
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white">//background color of your screen
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="put the resource id of the image you want to crop"
android:orientation="vertical" >
<View
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="@android:color/white" // background color of your screen
/>
</LinearLayout>
</LinearLayout>
Please tell me if there is any issue implementing it..
thanks enjoy,...
Upvotes: 1