如何使ImageButton成为一个圆圈并在该圆圈内适合Uploaded Image?

时间:2015-02-26 10:39:57

标签: android android-layout

我正在尝试在android中实现“上传个人资料Pic”的事情。以下是我需要在Android中实现的快照。

Snapshot_for_profile_page.png

enter image description here

我希望“添加照片”的工作方式与Instagram的编辑个人资料相同。 这是我到目前为止所做的工作。

  1. 我带了ImageButton。
  2. Onlcick事件我从相机/图库上传了图片。
  3. 但问题是正在上传的图像是平方的。 还有如何调整图像大小以适应该圆圈。我希望完整的图像能够完全融入圆圈。就像在Instagram上一样

    这是我的代码

    Profile.java

    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.support.v4.app.FragmentActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.ImageButton;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    
    
    public class Profile extends FragmentActivity {
    
        private ImageButton mProfileImage;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.profile_activity);
            mProfileImage = (ImageButton) findViewById(R.id.imageButton);
            mProfileImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectImage();
                }
            });
     }
    
        private void selectImage() {
            final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
            AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
            builder.setTitle("Add Photo!");
            builder.setItems(options,new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if(options[item].equals("Take Photo"))
                    {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                        startActivityForResult(intent, 1);
                    }
                    else if (options[item].equals("Choose from Gallery"))
                    {
                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 2);
                    }
                    else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
        @Override
    
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK) {
                if (requestCode == 1) {
                    File f = new File(Environment.getExternalStorageDirectory().toString());
                    for (File temp : f.listFiles()) {
                        if (temp.getName().equals("Image.jpg")) {
                            f = temp;
                            break;
                        }
                    }
                    try {
                        Bitmap bitmap;
                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
                        mProfileImage.setImageBitmap(bitmap);
                        String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Phoenix" + File.separator + "default";
                        f.  delete();
                        OutputStream outFile;
                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
    
                        try {
                            outFile = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                            outFile.flush();
                            outFile.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (requestCode == 2) {
                    Uri selectedImage = data.getData();
                    String[] filePath = { MediaStore.Images.Media.DATA };
                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                    mProfileImage.setImageBitmap(thumbnail);
    
                }
    
            }
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_profile, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            //int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
    
    
            return super.onOptionsItemSelected(item);
        }
    }
    

    profile_activity.xml

                    <ImageButton
                    android:layout_width="150dp"
                    android:layout_height="155dp"
                    android:id="@+id/imageButton"
                    android:src="@drawable/add_photo"
                    android:background="@drawable/circlebutton"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:adjustViewBounds="true"
                    android:scaleType="fitXY" />
    

    circlebutton.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">
        <solid android:color="#FFFFFF"/>
        <stroke android:width="1dp" android:color="#00A2B3" />
        <!--<corners
            android:bottomLeftRadius="12.0dip"
            android:bottomRightRadius="12.0dip"
            android:radius="12.0dip"
            android:topLeftRadius="12.0dip"
            android:topRightRadius="12.0dip" />-->
    </shape>
    

    按钮仍为方形。

    PS:对不起我的英文

2 个答案:

答案 0 :(得分:4)

只是一个与你的解决方案完全不同的技巧,

  1. 让图像保持正方形或其他形状。只需将其置于其父级内部即可。

  2. 放置另一张白色的imageView,中间有一个有边界的圆形空间,覆盖在该个人物照片上。

  3. 这称为掩蔽:)

答案 1 :(得分:3)

我建议你使用Picasso库。创建一个扩展毕加索的Transformation类的类。

public class RoundTransformation implements com.squareup.picasso.Transformation {

private final int radius;
private final int margin;

public RoundTransformation(final int radius, final int margin) {
    this.radius = radius;
    this.margin = margin;
}

@Override
public Bitmap transform( Bitmap source) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));



    Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() - margin, source.getHeight() - margin), radius, radius, paint);

    if (source != output) {
        source.recycle();
    }

    return output;
}

@Override
public String key() {
    return "rounded";
    }
}

准备好这堂课了。使用毕加索图书馆

Picasso.with(context).load("url")
            .transform(new RoundTransformation(radius,margin)).into(image);

PS:而不是使用ImageButton使用ImageView并在imageview上使用setOnClickListener