Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/183.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在android中缩小图像比例_Android_Android Layout_Android Imageview_Android Image - Fatal编程技术网

如何在android中缩小图像比例

如何在android中缩小图像比例,android,android-layout,android-imageview,android-image,Android,Android Layout,Android Imageview,Android Image,我正在创建一个android应用程序,我可以添加一个图像。但是,我想做的是缩小图像以适合ImageButton的大小。有办法吗 到目前为止,我编写的代码是: package awad865.project.ContactManager1; import java.io.FileNotFoundException; import java.io.InputStream; import android.app.Activity; import android.content.Intent;

我正在创建一个android应用程序,我可以添加一个图像。但是,我想做的是缩小图像以适合ImageButton的大小。有办法吗

到目前为止,我编写的代码是:

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);

        }
    }
}
包awad865.project.ContactManager1;
导入java.io.FileNotFoundException;
导入java.io.InputStream;
导入android.app.Activity;
导入android.content.Intent;
导入android.database.SQLException;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.drawable.BitmapDrawable;
导入android.net.Uri;
导入android.os.Bundle;
导入android.support.v4.app.NavUtils;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.EditText;
导入android.widget.ImageButton;
导入android.widget.Spinner;
公共类AddContact扩展活动{
//声明私有字段
私人编辑文本名;
私人编辑文本姓氏;
私人编辑文本编号;
专用文本地址;
私人编辑文本日期;
私人文本电子邮件;
私人纺纱机;
私人纺纱机;
专用微调器地址微调器;
私有微调器;
专用数据库处理程序DatabaseHandler;
私有图像按钮addPic;
私有最终整数图像_选择=1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u add\u contact);
//启用操作栏上标题的代码
getActionBar().setDisplayShowTitleEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
databaseHandler=新的databaseHandler(此);
//私有土地的更新
firstName=(EditText)findViewById(R.id.edit\u first\u name);
lastName=(EditText)findViewById(R.id.edit\u last\u name);
编号=(EditText)findViewById(R.id.edit_编号);
地址=(EditText)findViewById(R.id.edit_地址);
日期=(EditText)findViewById(R.id.edit_日期);
email=(EditText)findViewById(R.id.edit_email);
//电话号码字段的微调器
numberSpinner=(微调器)findViewById(R.id.contact\u number\u微调器);
//使用字符串数组和默认微调器布局创建ArrayAdapter
ArrayAdapter=ArrayAdapter.createFromResource(此,
R.array.number\u数组,android.R.layout.simple\u微调器\u项);
//指定显示选项列表时要使用的布局
setDropDownViewResource(android.R.layout.simple\u微调器\u下拉菜单\u项);
//将适配器应用于微调器
numberSpinner.setAdapter(适配器);
//电子邮件地址字段的微调器
emailSpinner=(Spinner)findViewById(R.id.contact\u email\u Spinner);
adapter=ArrayAdapter.createFromResource(此,
R.array.email_数组,android.R.layout.simple_微调器_项);
setDropDownViewResource(android.R.layout.simple\u微调器\u下拉菜单\u项);
emailSpinner.setAdapter(适配器);
//地址字段微调器
addressSpinner=(Spinner)findViewById(R.id.contact\u address\u Spinner);
adapter=ArrayAdapter.createFromResource(此,
R.array.address\u数组,android.R.layout.simple\u微调器\u项);
setDropDownViewResource(android.R.layout.simple\u微调器\u下拉菜单\u项);
addressSpinner.setAdapter(适配器);
//日期微调器
dateSpinner=(微调器)findViewById(R.id.contact\u date\u微调器);
adapter=ArrayAdapter.createFromResource(此,
R.array.date\u数组,android.R.layout.simple\u微调器\u下拉菜单\u项);
setDropDownViewResource(android.R.layout.simple\u微调器\u下拉菜单\u项);
dateSpinner.setAdapter(适配器);
addPic=(ImageButton)findViewById(R.id.addImage);
位图bm=BitmapFactory.decodeResource(getResources(),R.drawable.ic\u social\u person);
addPic.setImageBitmap(bm);
addPic.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图arg0){
Intent IMAGEINT=新意图(Intent.ACTION\U PICK);
setType(“image/*”);
startActivityForResult(图像意图、图像选择);
}
});
}
ActivityResult上受保护的void(int-requestCode、int-resultCode、Intent-ImageReturnedContent){
super.onActivityResult(请求代码、结果代码、图像返回内容);
开关(请求代码){
案例图像_选择:
if(resultCode==RESULT\u OK){
试一试{
BitmapFactory.Options=new-BitmapFactory.Options();
options.inScaled=true;
最终Uri imageURI=imageReturnedIntent.getData();
final InputStream inStr=getContentResolver().openInputStream(imageURI);
最终位图选择img=BitmapFactory.decodeStream(inStr,null,options);
addPic.setImageBitmap(选择img);
}捕获(FileNotFoundException ex){
Log.e(“未找到文件”,“未找到选定图像”,ex);
}
}
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.add_触点,菜单);
返回true;
}
公共布尔值onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
//如果按下保存按钮,则从编辑文本字段检索所有信息
//并存储在专用字段中,然后创建新的联系人对象并将其添加到
//数据库
案例R.id.action\u保存:
比特马
<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>
<ImageButton 
     android:scaleType="fitXY"
     ... />
android:layout_weight="1"
  <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" />
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;
    }