2013-10-21 48 views
1

我正在創建一個android應用程序,我可以添加圖片。但是,我想要做的是縮小圖像以適應ImageButton大小。有沒有辦法做到這一點?如何在android中縮放圖片

到目前爲止,我已經寫代碼:

package awad865.project.ContactManager1; 



import java.io.FileNotFoundException; 
import java.io.InputStream; 

import android.app.Activity; 
import android.content.Intent; 
import android.database.SQLException; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.drawable.BitmapDrawable; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v4.app.NavUtils; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.EditText; 
import android.widget.ImageButton; 
import android.widget.Spinner; 


public class AddContact extends Activity { 
    //declare private fields 
    private EditText firstName; 
    private EditText lastName; 
    private EditText number; 
    private EditText address; 
    private EditText date; 
    private EditText email; 
    private Spinner numberSpinner; 
    private Spinner emailSpinner; 
    private Spinner addressSpinner; 
    private Spinner dateSpinner; 
    private DatabaseHandler databaseHandler; 
    private ImageButton addPic; 
    private final int IMAGE_SELECTION =1; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_add_contact); 
     //code that enables the title on the action bar 
     getActionBar().setDisplayShowTitleEnabled(true); 
     getActionBar().setDisplayHomeAsUpEnabled(true); 
     databaseHandler = new DatabaseHandler(this); 

     //intialise private fields 
     firstName = (EditText)findViewById(R.id.edit_first_name); 
     lastName = (EditText)findViewById(R.id.edit_last_name); 
     number = (EditText)findViewById(R.id.edit_number); 
     address = (EditText)findViewById(R.id.edit_address); 
     date = (EditText)findViewById(R.id.edit_date); 
     email =(EditText)findViewById(R.id.edit_email); 


     //Spinner for the phone number field 
     numberSpinner = (Spinner) findViewById(R.id.contact_number_spinner); 
     // Create an ArrayAdapter using the string array and a default spinner layout 
     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, 
       R.array.number_array, android.R.layout.simple_spinner_item); 
     // Specify the layout to use when the list of choices appears 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     // Apply the adapter to the spinner 
     numberSpinner.setAdapter(adapter); 


     //Spinner for the email address field 
     emailSpinner = (Spinner) findViewById(R.id.contact_email_spinner); 
     adapter = ArrayAdapter.createFromResource(this, 
       R.array.email_array, android.R.layout.simple_spinner_item); 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     emailSpinner.setAdapter(adapter); 

     //Spinner for address field 
     addressSpinner = (Spinner) findViewById(R.id.contact_address_spinner); 
     adapter= ArrayAdapter.createFromResource(this, 
       R.array.address_array, android.R.layout.simple_spinner_item); 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     addressSpinner.setAdapter(adapter); 

     //Spinner for date 
     dateSpinner = (Spinner) findViewById(R.id.contact_date_spinner); 
     adapter=ArrayAdapter.createFromResource(this, 
       R.array.date_array, android.R.layout.simple_spinner_dropdown_item); 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     dateSpinner.setAdapter(adapter); 


     addPic = (ImageButton) findViewById(R.id.addImage); 
     Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_social_person); 
     addPic.setImageBitmap(bm); 

     addPic.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       Intent imageIntent = new Intent(Intent.ACTION_PICK); 
       imageIntent.setType("image/*"); 
       startActivityForResult(imageIntent, IMAGE_SELECTION); 

      } 
     }); 
    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){ 
     super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

     switch(requestCode){ 
     case IMAGE_SELECTION: 
      if(resultCode == RESULT_OK){ 
       try{ 
        BitmapFactory.Options options = new BitmapFactory.Options(); 
        options.inScaled = true; 
        final Uri imageURI = imageReturnedIntent.getData(); 
        final InputStream inStr = getContentResolver().openInputStream(imageURI); 
        final Bitmap selectImg = BitmapFactory.decodeStream(inStr, null, options); 
        addPic.setImageBitmap(selectImg); 
       }catch(FileNotFoundException ex){ 
        Log.e("File not found", "Selected image was not found", ex); 
       } 
      } 
      } 

    } 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.add_contact, menu); 
     return true; 
    } 

    public boolean onOptionsItemSelected(MenuItem item){ 

     switch(item.getItemId()){ 
     //if the save button is pressed, then all the information is retrieved from the EditText fields 
     //and stored in the private fields and then a new contact object is created and added to the 
     //database 
     case R.id.action_save: 
      BitmapDrawable bmd = ((BitmapDrawable) addPic.getDrawable()); 
      Bitmap photo = bmd.getBitmap(); 
      Contact contact = new Contact(firstName.getText().toString(),lastName.getText().toString(),number.getText().toString(), numberSpinner.getSelectedItem().toString(), email.getText().toString(), emailSpinner.getSelectedItem().toString(), date.getText().toString(), dateSpinner.getSelectedItem().toString(), address.getText().toString(), addressSpinner.getSelectedItem().toString(), "false"); 
      //add to database 

      try { 
       databaseHandler.openDataBase(); 
       databaseHandler.addContact(contact); 
       databaseHandler.close(); 
      } catch (SQLException sqle) { 
       throw sqle; 
      } 
      //go back to list of contacts 
      Intent intentMain = new Intent(getApplicationContext(),MainActivity.class); 
      intentMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intentMain); 
      return true; 

      //if the cancel button is pressed on the action bar then the user is navigate to MainActivity 
     case R.id.action_cancel: 
      Intent intentCancel = new Intent(this,MainActivity.class); 
      intentCancel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intentCancel); 
      return true; 
      //if the up button is pressed, then the user is taken back to the MainActivity 
     case android.R.id.home: 
      NavUtils.navigateUpFromSameTask(this); 
      return true; 

     default: 
      return super.onOptionsItemSelected(item); 

     } 
    } 
} 

XML文件:

<LinearLayout 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:orientation="vertical" 
    tools:context=".AddContact" > 

    <TextView 
     android:id="@+id/lbl_name" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="5dp" 
     android:layout_marginTop="10dp" 
     android:text="@string/heading_name" 
     android:textColor="#0ab2ea" /> 

    <View 
     android:id="@+id/view_name" 
     android:layout_width="wrap_content" 
     android:layout_height="1.5dp" 
     android:background="@drawable/blue_colour" /> 

    <LinearLayout 
     android:layout_width="337dp" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:weightSum="6" > 

     <EditText 
      android:id="@+id/edit_first_name" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:layout_weight="5" 
      android:hint="@string/hint_firstname" 
      android:inputType="textCapSentences" /> 

     <ImageButton 
      android:id="@+id/addImage" 
      android:layout_width="0dp" 
      android:layout_height="58dp" 
      android:layout_weight="1" 
      android:background="@drawable/ic_social_person" /> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="337dp" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:weightSum="6" > 

     <EditText 
      android:id="@+id/edit_last_name" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="5dp" 
      android:layout_weight="5" 
      android:hint="@string/hint_lastname" 
      android:inputType="textCapSentences" /> 
    </LinearLayout> 

    <TextView 
     android:id="@+id/lbl_number" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="5dp" 
     android:text="@string/heading_number" 
     android:textColor="#0ab2ea" /> 

    <View 
     android:id="@+id/view_number" 
     android:layout_width="wrap_content" 
     android:layout_height="1.5dp" 
     android:background="@drawable/blue_colour" /> 

    <LinearLayout 
     android:layout_width="337dp" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:weightSum="3" > 

     <EditText 
      android:id="@+id/edit_number" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="5dp" 
      android:layout_marginTop="10dp" 
      android:layout_weight="2" 
      android:hint="@string/hint_number" 
      android:inputType="number" /> 

     <Spinner 
      android:id="@+id/contact_number_spinner" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:layout_weight="1" /> 
    </LinearLayout> 

    <TextView 
     android:id="@+id/lbl_email" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="5dp" 
     android:text="@string/heading_email" 
     android:textColor="#0ab2ea" /> 

    <View 
     android:id="@+id/view_email" 
     android:layout_width="wrap_content" 
     android:layout_height="1.5dp" 
     android:background="@drawable/blue_colour" /> 

    <LinearLayout 
     android:layout_width="337dp" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:weightSum="3" > 

     <EditText 
      android:id="@+id/edit_email" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="5dp" 
      android:layout_marginTop="10dp" 
      android:layout_weight="2" 
      android:hint="@string/hint_email" 
      android:inputType="textEmailAddress" /> 

     <Spinner 
      android:id="@+id/contact_email_spinner" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:layout_weight="1" /> 
    </LinearLayout> 

    <TextView 
     android:id="@+id/lbl_address" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="5dp" 
     android:text="@string/heading_address" 
     android:textColor="#0ab2ea" /> 

    <View 
     android:id="@+id/view_address" 
     android:layout_width="wrap_content" 
     android:layout_height="1.5dp" 
     android:background="@drawable/blue_colour" /> 

    <LinearLayout 
     android:layout_width="337dp" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:weightSum="3" > 

     <EditText 
      android:id="@+id/edit_address" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="5dp" 
      android:layout_marginTop="10dp" 
      android:layout_weight="2" 
      android:hint="@string/hint_address" 
      android:inputType="textPostalAddress" /> 

     <Spinner 
      android:id="@+id/contact_address_spinner" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:layout_weight="1" /> 
    </LinearLayout> 

    <TextView 
     android:id="@+id/lbl_event" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="5dp" 
     android:text="@string/heading_event" 
     android:textColor="#0ab2ea" /> 

    <View 
     android:id="@+id/view_event" 
     android:layout_width="wrap_content" 
     android:layout_height="1.5dp" 
     android:background="@drawable/blue_colour" /> 

    <LinearLayout 
     android:layout_width="337dp" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:weightSum="3" > 

     <EditText 
      android:id="@+id/edit_date" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="5dp" 
      android:layout_marginTop="10dp" 
      android:layout_weight="2" 
      android:hint="@string/hint_date" 
      android:inputType="date" /> 

     <Spinner 
      android:id="@+id/contact_date_spinner" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" /> 
    </LinearLayout> 

</LinearLayout> 

任何幫助,將不勝感激。

回答

6

下面是一些代碼,可以幫助你:

替換此代碼

BitmapFactory.Options options = new BitmapFactory.Options(); 
        options.inScaled = true; 
        final Uri imageURI = imageReturnedIntent.getData(); 
        final InputStream inStr = getContentResolver().openInputStream(imageURI); 
        final Bitmap selectImg = BitmapFactory.decodeStream(inStr, null, options); 
        addPic.setImageBitmap(selectImg); 

下面

final Uri imageURI = imageReturnedIntent.getData(); 
        final InputStream inStr = new BufferedInputStream(getContentResolver().openInputStream(imageURI)); 

        int height = addPic.getHeight(); 
        int width = addPic.getWidth(); 

        BitmapFactory.Options options = new BitmapFactory.Options(); 
        options.inJustDecodeBounds = true; 
        BitmapFactory.decodeStream(inStr, null, options); 

        // Calculate inSampleSize 
        options.inSampleSize = calculateInSampleSize(options, width, height); 

        // Decode bitmap with inSampleSize set 
        options.inJustDecodeBounds = false; 

        try { 
         inStr.reset(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

        Bitmap selectImg = BitmapFactory.decodeStream(inStr, null, options); 
        addPic.setImageBitmap(selectImg); 

代碼而這個功能添加到您的類

public int calculateInSampleSize(
      BitmapFactory.Options options, int reqWidth, int reqHeight) { 
     // Raw height and width of image 
     final int height = options.outHeight; 
     final int width = options.outWidth; 
     int inSampleSize = 1; 

     if (height > reqHeight || width > reqWidth) { 

      // Calculate ratios of height and width to requested height and width 
      final int heightRatio = Math.round((float) height/(float) reqHeight); 
      final int widthRatio = Math.round((float) width/(float) reqWidth); 

      // Choose the smallest ratio as inSampleSize value, this will guarantee 
      // a final image with both dimensions larger than or equal to the 
      // requested height and width. 
      inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 
     } 

     return inSampleSize; 
    } 

欲瞭解更多信息,你可以參考http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

+0

Thanks :)您的代碼像魅力一樣工作! – user123456

+0

快樂:) –

+0

嘿!我收到一個錯誤。每當我添加來自相機文件夾的圖像它不起作用,但如果我從Whatsapp圖像文件夾它的工作。你知道錯誤可能是什麼嗎? – user123456

2

嘗試使用您ImageButton這個屬性:

<ImageButton 
    android:scaleType="fitXY" 
    ... /> 

希望這有助於:)

0

也許拿出這從您的ImageButton XML的ImageButton作爲

android:layout_weight="1" 
2

使用Scale屬性:

<ImageButton 
      android:id="@+id/addImage" 
      android:layout_width="0dp" 
      android:layout_height="58dp" 
      android:layout_weight="1" 
      android:scaleType="fitXY" 
      android:background="@drawable/ic_social_person" /> 
+0

看來,即使您指定了其他東西(fitCenter,fitCrop,...),也總是會使用「fitXY」縮放圖像 – Thomas