绘制圆角矩形和文字

public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int sp2px(Context context, float spValue) {  
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;  
        return (int) (spValue * fontScale + 0.5f);  
    }


public  Bitmap createFramedPhoto(Context context,String str,int y, int textSize, int color,float outerRadiusRat) {
y = dip2px(context, y);
textSize = sp2px(context, textSize);
//准备文字,测量文字的宽度和高度
Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
| Paint.DEV_KERN_TEXT_FLAG);
textPaint.setTextSize(textSize);
textPaint.setTypeface(Typeface.DEFAULT_BOLD); // 采用默认的宽度
textPaint.setColor(Color.WHITE);
int x = (int) textPaint.measureText(str+"哈");
int len = (int) textPaint.measureText("哈");
FontMetrics fm = textPaint.getFontMetrics(); 
   float height = fm.descent - fm.ascent; 
   float descent = fm.leading- fm.ascent;


        // 新建一个新的输出图片
        Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);


        // 新建一个矩形
        RectF outerRect = new RectF(0, 0, x, y);


        // 产生一个红色的圆角矩形
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(color);
        canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint);
canvas.drawText(String.valueOf(str), len/2, (y-height)/2+descent,
textPaint);
        canvas.save(canvas.ALL_SAVE_FLAG);
        canvas.restore();


        return output;
    }

你可能感兴趣的:(android)