如何将方形图像转换为椭圆形

时间:2012-01-23 12:13:38

标签: android android-layout

在我的应用程序中,我从图库中获取图像,并且该图像的形状在正方形中我想将该图像设置为imageView然后它应该是椭圆形状。在我的情况下,我需要像人脸一样裁剪图像。任何人都可以提前告诉我如何做到这一点。

3 个答案:

答案 0 :(得分:5)

使用以下类而不是图像视图。

 RoundedCornerImageView imageView1;
 imageView1.setRadius(10);

这将使图像半径为10像素,您可以给出您想要的值,并将其作为您想要的形状。试一试。

一切顺利:)

public class RoundedCornerImageView extends ImageView {
    private int radius = 10;

    public RoundedCornerImageView(Context context) {
        super(context);
    }

    protected void onDraw(Canvas canvas) {
        Path clipPath = new Path();
        int w = this.getWidth();
        int h = this.getHeight();
        clipPath.addRoundRect(new RectF(0, 0, w, h), radius, radius, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }

    public RoundedCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public RoundedCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setRadius(int radius){
        this.radius = radius;
        this.invalidate();
    }
}

答案 1 :(得分:4)

您可以使用此

public  Drawable getRoundedCornerImage(Drawable bitmapDrawable) {
        Bitmap bitmap = ((BitmapDrawable)bitmapDrawable).getBitmap();
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = 100;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        Drawable image = new BitmapDrawable(output);
        return image;

    }

希望这有助于你

答案 2 :(得分:-1)

enter image description here

您也可以使用此功能或Download demo code example

Trump

最后,在您的主要活动中,实例化您的类Shape并将两个参数传递给您的类。要裁剪为椭圆的图像以及将设置最终图像的imageview。

Download demo code example

相关问题