Android:在视图上屏蔽形状的最简单方法是什么?

时间:2015-08-18 18:29:04

标签: android android-layout layout fragment

我想创建一个圆形地图片段视图

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:transitionName="@string/map"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_width="200dp"
        android:layout_height="200dp"
        tools:context="com.example.gyang.android.MapActivity"
        class="com.google.android.gms.maps.SupportMapFragment"/>

目前我的片段是一个大广场。将此变为圆圈的最简单方法是什么?

3 个答案:

答案 0 :(得分:4)

您可以创建自定义视图并覆盖onDraw以执行蒙版。

public void draw(Canvas canvas) {
        Bitmap original = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.original_image);
        Bitmap mask = Bitmap.createBitmap(getContext().getResources(),R.drawable.mask_image);

        //You can change original image here and draw anything you want to be masked on it.

        Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Config.ARGB_8888);
        Canvas tempCanvas = new Canvas(result);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        tempCanvas.drawBitmap(original, 0, 0, null);
        tempCanvas.drawBitmap(mask, 0, 0, paint);
        paint.setXfermode(null);

        //Draw result after performing masking
        canvas.drawBitmap(result, 0, 0, new Paint());
}

this帖子中获取的代码。

答案 1 :(得分:0)

试试这个:

public void draw(Canvas canvas) {

    Bitmap original = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.original_image);
    Bitmap mask = Bitmap.createBitmap(getContext().getResources(),R.drawable.mask_image);

    //You can change original image here and draw anything you want to be masked on it.
    Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Config.ARGB_8888);
    Canvas tempCanvas = new Canvas(result);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
    tempCanvas.drawBitmap(original, 0, 0, null);
    tempCanvas.drawBitmap(mask, 0, 0, paint);
    paint.setXfermode(null);

    //Draw result after performing masking
    canvas.drawBitmap(result, 0, 0, new Paint());
}

答案 2 :(得分:0)

对我来说,最简单的使中间透明的形状是通过构造带有视图的外部零件:topBox,rightBox,bottomBox,leftBox并将中间留为空白。 我还需要有圆角,为此,我使用SVG图像来模拟透明中间形状的角。

enter image description here