How to set selected area of Image to ImageView

孤人 提交于 2019-12-06 07:58:12

问题


I Was trying to set image to imageimageviewview from external storage and I done with that, but the thing is that it sets the whole image to imageview and I only want to set the selected square area from that image. Just life facebook provided functionality to set profile pic.. Can any one help me to do it?? Following is the sample what i want to do..


回答1:


Something like this:

public static Bitmap cropBitmapToSquare(Bitmap bmp) {

    System.gc();
    Bitmap result = null;
    int height = bmp.getHeight();
    int width = bmp.getWidth();
    if (height <= width) {
        result = Bitmap.createBitmap(bmp, (width - height) / 2, 0, height,
                height);
    } else {
        result = Bitmap.createBitmap(bmp, 0, (height - width) / 2, width,
                width);
    }
    return result;
}

Here is a sample with crop activity:

http://khurramitdeveloper.blogspot.ru/2013/07/capture-or-select-from-gallery-and-crop.html




回答2:


actually my comment above about setImageMatrix was not the best solution, try this custom Drawable (no need to allocate any temporary Bitmaps):

class CropDrawable extends BitmapDrawable {

    private Rect mSrc;
    private RectF mDst;

    public CropDrawable(Bitmap b, int left, int top, int right, int bottom) {
        super(b);
        mSrc = new Rect(left, top, right, bottom);
        mDst = new RectF(0, 0, right - left, bottom - top);
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawBitmap(getBitmap(), mSrc, mDst, null);
    }

    @Override
    public int getIntrinsicWidth() {
        return mSrc.width();
    }

    @Override
    public int getIntrinsicHeight() {
        return mSrc.height();
    }
}

and testing code:

    ImageView iv = new ImageView(this);
    Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.test);
    Drawable d = new CropDrawable(b, 150, 100, 180, 130);
    iv.setImageDrawable(d);
    setContentView(iv);


来源:https://stackoverflow.com/questions/21701447/how-to-set-selected-area-of-image-to-imageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!