Lập trình Android — August 2, 2016 at 2:42 am

Code tính năng zoom ảnh trong ứng dụng Android

by

Hiện nay khi truy cập vào một website nào đó để tìm các tấm ảnh đẹp, các bạn để ý khi click vào thì tấm ảnh sẽ phóng to ra giữa màn hình hay còn gọi là tính năng zoom để chúng ta có thể nhìn rõ ràng hơn. Làm thế nào người ta làm được như thế?. Đối với lập trình Android thì code như thế nào. Hãy cùng theo dõi nhé.

 

1) Giới thiệu thêm về Zoom Image:

– Zoom Image là gì? Đơn giản là nó phóng to một hình ảnh cụ thể nào đó lên toàn bộ màn hình hiển thị và ngược lại là thu nhỏ nó về vị trí cũ.

– Lợi ích của việc Zoom Image: việc phóng to sẽ giúp người dùng xem rõ chi tiết một hình nào đó mà người dùng mong muốn.

2) Hướng dẫn code:

– res/values/strings.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>

<string name=”parsed_data”>http://android.vn\nHướng dẫn bởi thanhlong90.it</string>
<string name=”app_name”>DemoAndroidZoomImage</string>
<string name=”action_settings”>Settings</string>
<string name=”hello_world”>Hello world!</string>

</resources>

– activity_main.xml

<FrameLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/container”
android:layout_width=”match_parent”
android:layout_height=”match_parent” >

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”
android:padding=”16dp” >

<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”5dp”
android:gravity=”center”
android:text=”@string/parsed_data”
android:textAppearance=”?android:attr/textAppearanceMedium”
android:textStyle=”bold” />

<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”16dp”
android:orientation=”horizontal” >

<thanhlong90.it.demoandroidzoomimage.TouchHighlightImageButton
android:id=”@+id/thumb_button_1″
android:layout_width=”100dp”
android:layout_height=”75dp”
android:layout_marginRight=”1dp”
android:contentDescription=”@string/app_name”
android:scaleType=”centerCrop”
android:src=”@drawable/thumb1″ />

<thanhlong90.it.demoandroidzoomimage.TouchHighlightImageButton
android:id=”@+id/thumb_button_2″
android:layout_width=”100dp”
android:layout_height=”75dp”
android:contentDescription=”@string/app_name”
android:scaleType=”centerCrop”
android:src=”@drawable/thumb2″ />
</LinearLayout>
</LinearLayout>

<ImageView
android:id=”@+id/expanded_image”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:contentDescription=”@string/app_name”
android:visibility=”invisible” />

</FrameLayout>

– TouchHighlightImageButton.java

package com.example.android.animationsdemo;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageButton;

public class TouchHighlightImageButton extends ImageButton {
private Drawable mForegroundDrawable;

private Rect mCachedBounds = new Rect();

public TouchHighlightImageButton(Context context) {
super(context);
init();
}

public TouchHighlightImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public TouchHighlightImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}

private void init() {
setBackgroundColor(0);
setPadding(0, 0, 0, 0);

// Retrieve the drawable resource assigned to the android.R.attr.selectableItemBackground
// theme attribute from the current theme.
TypedArray a = getContext().obtainStyledAttributes(new int[]{android.R.attr.selectableItemBackground});
mForegroundDrawable = a.getDrawable(0);
mForegroundDrawable.setCallback(this);
a.recycle();
}

@Override
protected void drawableStateChanged() {
super.drawableStateChanged();

// Update the state of the highlight drawable to match
// the state of the button.
if (mForegroundDrawable.isStateful()) {
mForegroundDrawable.setState(getDrawableState());
}

// Trigger a redraw.
invalidate();
}

@Override
protected void onDraw(Canvas canvas) {
// First draw the image.
super.onDraw(canvas);

// Then draw the highlight on top of it. If the button is neither focused
// nor pressed, the drawable will be transparent, so just the image
// will be drawn.
mForegroundDrawable.setBounds(mCachedBounds);
mForegroundDrawable.draw(canvas);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);

// Cache the view bounds.
mCachedBounds.set(0, 0, w, h);
}
}

– MainActivity.java

package thanhlong90.it.demoandroidzoomimage;

import android.os.Bundle;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;

public class MainActivity extends Activity {
private Animator mCurrentAnimator;
private int mShortAnimationDuration;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final View thumb1View = findViewById(R.id.thumb_button_1);
thumb1View.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
zoomImageFromThumb(thumb1View, R.drawable.image1);
}
});

final View thumb2View = findViewById(R.id.thumb_button_2);
thumb2View.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
zoomImageFromThumb(thumb2View, R.drawable.image2);
}
});

mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}

private void zoomImageFromThumb(final View thumbView, int imageResId) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}

final ImageView expandedImageView = (ImageView) findViewById(R.id.expanded_image);
expandedImageView.setImageResource(imageResId);
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container).getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
float startScale;
if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds.width() / startBounds.height()) {
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth – startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight – startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}

thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);

expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);

AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}

@Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;

final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}

AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X,startBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScaleFinal))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}

@Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
}
});
}
}

 

Còn chần chừ gì nữ hãy chạy lên và xem kết quả thế nào nhé.

Cảm ơn các bạn đã theo dõi !

Nguồn android.vn

Leave a Comment

Your email address will not be published. Required fields are marked *