我需要创建一个包含ImageView和TextView的FrameLayout。如何创建一个圆角布局,使它们显示为图像中所示?我尝试将圆形形状添加到布局的背景中,但它不起作用。
<com.stelladk.arclib.ArcLayout
android:layout_width="200dp"
android:layout_height="200dp"
app:ArcType="inner"
app:ArcRadius="100dp"
android:background="@drawable/scenery">
<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:text="Change"
android:background="@color/semiwhite"
android:gravity="center"
android:layout_gravity="bottom"/>
</com.stelladk.arclib.ArcLayout>
我有一个类可以完成相同的工作,你可以参考一下,在包内添加这个类并使用:
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
if (b == null) {
return;
}
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
if(bitmap ==null)
{
return;
}
int w = getWidth(), h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xffa19774;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
使用这种类型的XML进行设计。<com.packagename.RoundedImageView
android:id="@+id/odd_bubble"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_alignParentLeft="true"
android:layout_margin="5dip"
android:src="@drawable/index"
/>
onDraw
中使用canvas.drawText()
来放置文本。现在创建一个扩展FrameLayout
或RelativeLayout
的新类,并将上述自定义视图类和RoundedImageView类用作内部类。现在在父类中填充这两个视图。现在您可以获得圆形图像以及其下方的文本。drawText()
方法传递适当的参数,以便它对齐到所需位置。