JavascriptProva

lunedì 18 aprile 2016

Studio per l'adattamento e la centratura delle immagini in un contenitore.

Se un'immagine è contenuta in un contenitore, ne assume la larghezza.
Provo:
  //CREAZIONE DEL LAYOUT
  layout=new RelativeLayout(this);
  BitmapDrawable sfondo=(BitmapDrawable)this.getResources().getDrawable(R.drawable.cartella);
  layout.setBackground(sfondo);
  
  //settaggio dei parametri
  LayoutParams lParams=new LayoutParams(LayWidth,LayHeight);
  lParams.leftMargin=LayLeft;
  lParams.topMargin=LayTop;
  layout.setLayoutParams(lParams);
  
  
  //CREAZIONE DELL'IMMAGINE
  ImageView imageView =new ImageView(this);
  BitmapDrawable immagine=(BitmapDrawable)this.getResources().getDrawable(R.drawable.chiave);
  imageView.setImageDrawable(immagine);
  
  //definizione delle dimensioni
  ImgWidth=immagine.getBitmap().getWidth();
  ImgHeight=immagine.getBitmap().getHeight();
  
  //scaletype
  imageView.setScaleType(ImageView.ScaleType.FIT_START);
  Log.v(""+ImgWidth,""+ImgHeight);
  
  //settaggio dei parametri
  LayoutParams imgParams=new LayoutParams(ImgWidth,ImgHeight);
  imgParams.leftMargin=ImgLeft;
  imgParams.topMargin=ImgTop;
  imageView.setLayoutParams(imgParams);
Ecco: qui ottengo questi valori di larghezza e altezza dell'immagine:
04-17 21:52:23.285: V/406(2224): 175

ossia 406 e 175.

Ma le dimensioni del Layout contenitore sono 100 e 100:
  int LayLeft, LayTop, LayWidth, LayHeight;
  int ImgLeft, ImgTop, ImgWidth, ImgHeight;
  LayLeft=0;
  LayTop=0;
  LayWidth=100;
  LayHeight=100;
  
  ImgLeft=0;
  ImgTop=0;
Bisogna rapportare quindi le dimensioni dell'immagine a quelle del contenitore.



Ecco infine la funzione che ho creato, in cui bisogna fornire una scalatura, una ImageView, la bitmap e le dimensioni del contenitore:
 public void centerImage(float Scalatura, ImageView imgView, 
   BitmapDrawable bitmapDrawable,int ContWidth, int ContHeight){
  int ImgWidth=bitmapDrawable.getBitmap().getWidth();
  int ImgHeight=bitmapDrawable.getBitmap().getHeight();
  float Scala=Scalatura;
  if(ImgWidth>ImgHeight) {
   float Ratio=(float)ImgHeight/(float)ImgWidth;
   ImgWidth=(int) (ContWidth*Scala);
   ImgHeight=(int)(ImgWidth*Ratio);
  }else{
   float Ratio=(float)ImgWidth/(float)ImgHeight;
   ImgHeight=(int)(ContHeight*Scala);
   ImgWidth=(int)(ImgHeight*Ratio);
  }
  
  int ImgTop=ContHeight/2-ImgHeight/2;
  int ImgLeft=ContWidth/2-ImgWidth/2;
  
  imgView.setScaleType(ImageView.ScaleType.FIT_START);
  LayoutParams imgParams=new LayoutParams(ImgWidth,ImgHeight);
  imgParams.leftMargin=ImgLeft;
  imgParams.topMargin=ImgTop;
  imgView.setLayoutParams(imgParams);
 }


Nessun commento:

Posta un commento