YouluUtil public static Bitmap getAvatar(Context context, int photoId) {擷取我的頭像 Bitmap bitmap = null; if(photoId==0){ //沒有為連絡人設定頭像 //手動指定一個頭像 //bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher); bitmap = getMyAvatar(context); }else{ //有頭像,DATA資料表中的data15列 ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(Data.CONTENT_URI, new String[]{Data.DATA15}, 根據Id查頭像 Data._ID + " = ?", new String[]{String.valueOf(photoId)}, null); cursor.moveToNext();//指向第一條資料 byte[] bytes = cursor.getBlob(0); //方形圖 Bitmap avatar = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); cursor.close(); bitmap = getCircleAvatar(context,avatar); } return bitmap; } private static Bitmap getCircleAvatar(Context context, Bitmap avatar) { Bitmap bitmap = Bitmap.createBitmap(avatar.getWidth(), avatar.getHeight(), Bitmap.Config.ARGB_8888); 位元影像位元越高代表其可以儲存的顏色資訊越多,當然映像也就越逼真 Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLACK); float radius = Math.min(avatar.getWidth(), avatar.getHeight())/2;擷取半徑 //混合模式中的DST canvas.drawCircle(avatar.getWidth()/2, avatar.getHeight()/2, radius , paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));設定前景後景模式 //混合模式中的SRC canvas.drawBitmap(avatar, 0, 0, paint); //畫白邊 paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.STROKE); float strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, context.getResources().getDisplayMetrics());螢幕的密度,類似解析度 paint.setStrokeWidth(strokeWidth); canvas.drawCircle(avatar.getWidth()/2, avatar.getHeight()/2, radius-strokeWidth/2, paint); return bitmap; } /** * 手動繪製一個頭像出來 * 深灰色背景,前景白色文字“友錄” * @return */ private static Bitmap getMyAvatar(Context context) { Bitmap bitmap = Bitmap.createBitmap(150, 150, Bitmap.Config.ARGB_8888); //繪製圖形需要2個對象 //畫布Canvas Canvas canvas = new Canvas(bitmap); //畫筆Paint Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.DKGRAY); paint.setStyle(Style.FILL); canvas.drawCircle(75, 75, 75, paint); paint.setColor(Color.WHITE); //sp--螢幕的密度-->px int sp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, context.getResources().getDisplayMetrics()); paint.setTextSize(sp); Rect bounds = new Rect(); paint.getTextBounds("友錄", 0, 2, bounds ); float x = 75 - bounds.width()/2; float y = 75 + bounds.height()/2; canvas.drawText("友錄", x, y, paint); //畫白邊 paint.setStyle(Paint.Style.STROKE); float strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, context.getResources().getDisplayMetrics()); paint.setStrokeWidth(strokeWidth); canvas.drawCircle(75, 75, 75-strokeWidth/2, paint); return bitmap; } } |