繁体   English   中英

Android创建具有3个圆角和1个直角的ImageView

[英]Android Create ImageView with 3 rounded and 1 straight corner

我想创建一个3个圆角和一个直角的图像视图。

设置背景可绘制不起作用,我确实找到了一些Java代码,但它仅将2个角或4个角倒圆,而不是3个角

Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Bitmap.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 = pixels;

paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

paint.setXfermode(new 
PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

return output;

结果图像应为附件

在可绘制文件中创建新的可绘制资源文件,并将背景设置为可绘制文件。

<shape xmlns:android="http://schemas.android.com/apk/res/android">

<!-- set the transparent background to image view -->
    <solid android:color="#00000000" />

<!-- Replace the corner value with suitable value -->
    <corners android:bottomLeftRadius="0dp"
        android:bottomRightRadius="0dp"
        android:topLeftRadius="0dp"
        android:topRightRadius="0dp" />
</shape>

并在xml文件中应用适当的scaletype属性。

  1. CENTER –将图片居中,但不缩放图片
  2. CENTER_CROP –均匀CENTER_CROP图像
  3. CENTER_INSIDE –将图像居中放置在容器中
  4. FIT_CENTER –从中心缩放图像
  5. FIT_END –从容器末端缩放图像。
  6. FIT_START –从容器的开始缩放图像
  7. FIT_XY –从容器的x和y坐标填充图像
  8. MATRIX –绘图时使用图像矩阵进行缩放

那里有写得很好的库,您可以将图像剪切到所需的任何路径,但这是代码:

private Bitmap clip(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
            .getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final Paint paint = new Paint();
    paint.setAntiAlias(true);


    // creating a closing path with 3 rounded corners
    Path path = new Path();
    float radius = 48;
    float diameter = radius * 2;
    float width = bitmap.getWidth();
    float height = bitmap.getHeight();
    path.addArc(0, 0, diameter, diameter, 180, 90);
    path.lineTo(width - radius, 0);
    path.arcTo(width - diameter, 0, width, diameter, 270, 90, false);
    path.lineTo(width, height);
    path.lineTo(radius, height);
    path.arcTo(0, height - diameter, diameter, height, 90, 90, false);
    path.close();


    paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    canvas.drawPath(path, paint);

    return output;

}

在Drawable @ background.xml文件中使用以下代码。

 <corners android:topLeftRadius="6dp" 
      android:topRightRadius="6dp"
      android:bottomLeftRadius="6dp" 
      android:bottomRightRadius="0dp"/>

然后用作Imageview的背景

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM