在您的问题上花费了数小时的时间后,我终于实现了,希望现在它会给您带来与您想要的相同的结果,请通过下面的代码让我知道它是否有效?
将适当的参数传递给下面的函数以获得带有您想要的颜色边框的圆角。
public static Bitmap getRoundedCornerImage(Bitmap bitmap, int cornerDips, int borderDips, Context context) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int borderSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) borderDips,
context.getResources().getDisplayMetrics());
final int cornerSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) cornerDips,
context.getResources().getDisplayMetrics());
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
paint.setColor(0xFFFFFFFF);
paint.setStyle(Paint.Style.FILL);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
paint.setColor((Color.RED)); // you can change color of your border here, to other color
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth((float) borderSizePx);
canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint);
return output;
}
主要的.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
创建时
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView rl=(ImageView)findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.testing); // your desire drawable image.
rl.setImageBitmap(getRoundedCornerImage(bitmap, 10, 10, this));
}
原始图像
输出
下面的链接帮助我实现我的目标:
Android中圆角位图的边框
创建带圆角的 ImageView
如何使 ImageView 具有圆角
如何设置paint.setColor(int color)