Your question was as much as complex and at the same time without goals for the goal:screen image on android. Well... Let’s get out of the critics and go for my answer.
Suposição e lógica
:
Imagining that you want the customer to download a particular image, when starting the app, and, that it gets saved inside the images folder of your own device. What’s the point? I don’t know... What’s new about something? Then it would be necessary to download the image of a url externa
and convert it to bitmap
and thus display in a ImageView
And ALSO, by clicking on it, it would be good to create a kind of lightbox
so that it does not occupy so much space on the device screen with a fixed size, set. With all this, it would be easy to update all clients, with only one image, coming from an external server, because you could change it whenever you wanted, otherwise it would be inside drawble
.
1.MainActivity. class
package app.test;
import java.io.File;
import android.app.Activity;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnTouchListener{
//ISTO DETERMINA O TAMANHO DA IMAGEM DEPOIS DO TOQUE
private float mScaleFactor = 6f;
private float globalX;
private Matrix mMatrix = new Matrix();
private float mFocusX = 0.f;
private float mFocusY = 0.f;
private int mImageHeight = 0;
private Uri caminho;
ImageLoader imageLoader = new ImageLoader();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Isto esconde o erro na hora de baixar o bitmap para as versões mais atuais do SDK
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//Criando a novos diretórios somente INSTALAR O APP
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"/MeuApp/Imagens/");
directory.mkdirs();
}
//Obtendo DisplayMetrics do dispositivo: largura e altura.
DisplayMetrics displayMetrics = getBaseContext().getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
//Altere o valor atual: 10f, para um valor que desejar. Isto posicionará a imagem
mFocusX = width/10f;
mFocusY = height/10f;
ImageView view = (ImageView) findViewById(R.id.ImageView);
//**2 passos para baixar a imagem, por isso os códigos devem está nessa ordem
// 1 - Toda vez que o app for iniciado, ele ira baixar a imagem. Esta linha de código pode está onde desejar
imageLoader.baixando();
// 2 - Caminho da imagem baixada
caminho = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MeuApp/Imagens/" + "imagem" );
view.setImageURI(caminho);
// Setando esta classe em touchListener para a ImageView
view.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
//Se a posição 'x', no plano cartesiano, for menor que 102.4
if (globalX < 102.4){
//Setando uma nova escala para x e y, no plano
float scaledImageCenterX = (mImageHeight*mScaleFactor)/2;
float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;
//Mudando escala
mMatrix.postScale(mScaleFactor, mScaleFactor);
//Mudando a transação
mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY);
//Setando as novas configurações da ImageView
ImageView view = (ImageView) v;
view.setImageMatrix(mMatrix);
//Salvando valor da posição x na variável globalX através do Matrix
float[] values = new float[9];
mMatrix.getValues(values);
globalX = values[Matrix.MTRANS_X];
return false;
}else{
// AQUI ACONTECE A REVERSÃO DO TAMANHO ATRAVÉS DA FUNÇÃO reset();
mMatrix.reset();
//Setando as novas configurações da ImageView
ImageView view = (ImageView) v;
view.setImageMatrix(mMatrix);
// zerando a posição x para a condicional ser refeita
globalX = 0;
}
return false;
}
}
2.ImageLoader. class
package app.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
public class ImageLoader {
//Conexão, baixando e convertendo
public Bitmap getBitmapFromURL(String url) {
try {
URL src = new URL(url);
HttpURLConnection connection = (HttpURLConnection) src.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
//Salvando o Bitmap na pasta do app
public void salvando(Bitmap abmp){
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MeuApp/Imagens/";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "imagem");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
;
abmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//Executando os métodos: salvando e getBitmapFromURL
public void baixando() {
salvando(getBitmapFromURL("http://www.meusite.net/imagens/MATENHAesteTITULO.jpg"));
return;
}
}
3.activity_main. xml
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="app.test.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toque na Imagem" />
<ImageView
android:id="@+id/ImageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:scaleType="matrix"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
Don’t forget to add this to Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
DOUBTS? Leave a comment!
What is the image? Where is it?
– ramaral
I am making a code where you click on the image and it grows by taking the screen of the device and when you click again it decreases.
– Lollipop
I’m done, Rodolfo, you want?
– Lollipop
Where will these images be? In an app folder?
– Lollipop