最近項(xiàng)目需要實(shí)現(xiàn)Android截屏分享功能,包括Android截屏獲取圖片、將圖片保存到本地、通知系統(tǒng)相冊(cè)更新、通過(guò)微信、QQ、微博分享截屏圖片,本篇文章作為總結(jié)回顧。
成都創(chuàng)新互聯(lián)專注于北鎮(zhèn)企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城建設(shè)。北鎮(zhèn)網(wǎng)站建設(shè)公司,為北鎮(zhèn)等地區(qū)提供建站服務(wù)。全流程按需求定制設(shè)計(jì),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
一、Android截屏獲取圖片
通過(guò)對(duì)view進(jìn)行繪制,得到bitmap,可以對(duì)Activity、Fragment進(jìn)行繪制,也可以對(duì)其他的View進(jìn)行繪制。
1 Activity截圖(帶空白的狀態(tài)欄)
public Bitmap shotScreen(Activity activity) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.setDrawingCacheEnabled(false); view.destroyDrawingCache(); return bitmap; }
2 Activity截圖(去掉狀態(tài)欄)
public Bitmap shotActivityNoBar(Activity activity) { // 獲取windows中最頂層的view View view = activity.getWindow().getDecorView(); view.buildDrawingCache(); // 獲取狀態(tài)欄高度 Rect rect = new Rect(); view.getWindowVisibleDisplayFrame(rect); int statusBarHeights = rect.top; Display display = activity.getWindowManager().getDefaultDisplay(); // 獲取屏幕寬和高 int widths = display.getWidth(); int heights = display.getHeight(); // 允許當(dāng)前窗口保存緩存信息 view.setDrawingCacheEnabled(true); // 去掉狀態(tài)欄 Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0, statusBarHeights, widths, heights - statusBarHeights); // 銷毀緩存信息 view.destroyDrawingCache(); return bmp; }
3 Fragment截圖
public Bitmap getFragmentBitmap(Fragment fragment) { View v = fragment.getView(); v.buildDrawingCache(false); return v.getDrawingCache(); }
繪制View的方式只適用于靜態(tài)View,SurfaceView、IjkVideoView等播放視頻的View,不能截取到;此外,某些動(dòng)畫類View也不能截取到。針對(duì)上述情況,可獲取SurfaceView的一幀生成bitmap,將bitmap進(jìn)行合并,同理動(dòng)畫類View也可以合并。例如,最底層播放視頻、中間層播放動(dòng)畫、最上層是普通的view,可將bitmap合并,如下:
public Bitmap combineBitmapInCenter(Bitmap background, Bitmap midBitmap, Bitmap foreground) { if (!background.isMutable()) { background = background.copy(Bitmap.Config.ARGB_8888, true); } Paint paint = new Paint(); Canvas canvas = new Canvas(background); int bw = background.getWidth(); int bh = background.getHeight(); int mw = midBitmap.getWidth(); int mh = midBitmap.getHeight(); int mx = (mw - bw) / 2; int my = (mh - bh) / 2; canvas.drawBitmap(midBitmap, mx, my, paint); int fw = foreground.getWidth(); int fh = foreground.getHeight(); int fx = (fw - bw) / 2; int fy = (fh - bh) / 2; canvas.drawBitmap(foreground, fx, fy, paint); canvas.save(Canvas.ALL_SAVE_FLAG); canvas.restore(); return background; }
需要注意:view的繪制必須在UI線程完成,否則會(huì)crash;bitmap的合并會(huì)較耗時(shí),需在子線程完成。
二 、將bitmap保存在本地
public void saveBitmapToFile(String fileName, Bitmap bitmap) { if (TextUtils.isEmpty(fileName) || bitmap == null) return; try { File f = new File(fileName); f.createNewFile(); FileOutputStream fOut = new FileOutputStream(f); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fOut); fOut.flush(); fOut.close(); } catch (FileNotFoundException e) { Log.i("ScreenShotUtil", "保存失敗"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
三、通知系統(tǒng)相冊(cè)更新
public void AlbumScan(String fileName) { MediaScannerConnection.scanFile(mActivity.getApplicationContext(), new String[]{fileName}, new String[]{"image/jpeg"}, null); }
四、通過(guò)微信、QQ、微博分享
通過(guò)微信、QQ、微博分享的sdk實(shí)現(xiàn),如下:
1 分享到微信朋友圈
public void shareToWexinCircle() { if (iShareService.isWeixinInstalled()) {//判斷微信是否安裝 Bitmap mWXShareBitmap = mLatesBitmap;//將截屏得到的bitmap賦值 WXImageObject imgObject = new WXImageObject(mWXShareBitmap); WXMediaMessage mediaMessage = new WXMediaMessage(); mediaMessage.mediaObject = imgObject; Log.i(TAG,"mediaMessage.mediaObject = imgObject"); //設(shè)置縮略圖 Bitmap thumbBmp = Bitmap.createScaledBitmap(mWXShareBitmap,50,80,true); mediaMessage.thumbData = bmpToByteArray(thumbBmp,true); Log.i(TAG,"設(shè)置縮略圖"); //request to wx SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("img");//分享類型是圖片 req.message = mediaMessage; req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈 Log.i(TAG,"request to wx"); IWXAPI api = WXAPIFactory.createWXAPI(mActivity,"微信分享id",true); api.registerApp("微信分享id"); boolean result = api.sendReq(req); Log.i(TAG,"share to circle:"+result); } else { ToastUtils.show(mActivity, "您沒(méi)有安裝微信客戶端"); } } public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) { ByteArrayOutputStream output = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, output); if (needRecycle) { bmp.recycle(); } byte[] result = output.toByteArray(); try { output.close(); } catch (Exception e) { e.printStackTrace(); } return result; }private String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); }
2、分享到微信好友
public void shareWexinFriend() { if (iShareService.isWeixinInstalled()) { mWXShareBitmap = mLatesBitmap; WXImageObject imgObject = new WXImageObject(mWXShareBitmap); WXMediaMessage mediaMessage = new WXMediaMessage(); mediaMessage.mediaObject = imgObject; //設(shè)置縮略圖 Bitmap thumbBmp = Bitmap.createScaledBitmap(mWXShareBitmap,50,80,true); mediaMessage.thumbData = bmpToByteArray(thumbBmp,true); //request to wx SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction =buildTransaction("img"); req.message = mediaMessage; req.scene = SendMessageToWX.Req.WXSceneSession; IWXAPI api = WXAPIFactory.createWXAPI(mActivity,"微信分享id",true); api.registerApp("微信分享id"); boolean result = api.sendReq(req); Log.i(TAG,"share to weixin:"+result ); } else { ToastUtils.show(mActivity, "您沒(méi)有安裝微信客戶端"); } }3、分享到QQ好友
public void shareToQQFriend() { if (iShareService.isQQInstalled()) {//判斷QQ是否安裝 Tencent tencent = Tencent.createInstance("qq id", mActivity); Bundle params = new Bundle(); params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, mLatestImagePath);//QQ分享只能分享本地圖片,傳入本地圖片路徑 params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE); tencent.shareToQQ(mActivity, params, new IUiListener() {//分享后的回調(diào) @Override public void onComplete(Object o) { ToastUtils.show(mActivity,"分享成功!"); } @Override public void onError(UiError uiError) { ToastUtils.show(mActivity,"分享失敗,稍后重試!"); Log.i(TAG,"shareToQQ onError"); } @Override public void onCancel() { Log.i(TAG,"shareToQQ onCancel"); } }); } else { ToastUtils.show(mActivity, "您沒(méi)有安裝QQ客戶端"); } }
4 QQ空間分享
public void shareToQQZone() { if (iShareService.isQQInstalled()) { Tencent tencent = Tencent.createInstance("QQ id", mActivity); Bundle params = new Bundle(); params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, mLatestImagePath); params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE); params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN); tencent.shareToQQ(mActivity, params, new IUiListener() { @Override public void onComplete(Object o) { ToastUtils.show(mActivity,"分享成功!"); } @Override public void onError(UiError uiError) { ToastUtils.show(mActivity,"分享失敗,請(qǐng)稍后重試!"); Log.i(TAG,"shareToQQ onError,error code:"+uiError.errorCode); } @Override public void onCancel() { Log.i(TAG,"shareToQQ onCancel"); } }); } else { ToastUtils.show(mActivity, "您沒(méi)有安裝QQ客戶端"); }
5 微博分享
public void shareToWeibo() { if (iShareService.isWeiboInstalled()) { Log.i(TAG,"iShareService.isWeiboInstalled()"); IWeiboShareAPI api = WeiboShareSDK.createWeiboAPI(mActivity, "微博id"); if(api.isWeiboAppInstalled()) { api.registerApp(); } WeiboMultiMessage weiboMultiMessage = new WeiboMultiMessage(); Bitmap bitmap = mLatesBitmap;//截圖bitmap ImageObject imageObject = new ImageObject(); imageObject.setImageObject(bitmap); weiboMultiMessage.imageObject = imageObject; SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest(); request.transaction = String.valueOf(System.currentTimeMillis()); request.multiMessage = weiboMultiMessage; boolean requestWeibo = api.sendRequest(request); Log.i(TAG,"share to weibo:"+requestWeibo ); } else { ToastUtils.show(mActivity, "您沒(méi)有安裝微博客戶端"); } }
總結(jié)
以上所述是小編給大家介紹的Android截屏分享功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)創(chuàng)新互聯(lián)網(wǎng)站的支持!