iOS Android 截屏分享图片,&& iOS自定义图片分享

本文介绍在Android和iOS平台上实现应用内截图功能的方法,并演示如何将截图分享至社交平台。包括创建截图类、捕获屏幕内容、保存为图片文件及通过Intent或通知进行分享的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 Android


创建ScreenShot类来进行截图处理,并返回保存的文件名

  1. public class ScreenShot {  
  2.     // 获取指定Activity的截屏,保存到png文件  
  3.     private static Bitmap takeScreenShot(Activity activity) {  
  4.         // View是你需要截图的View  
  5.         View view = activity.getWindow().getDecorView();  
  6.         view.setDrawingCacheEnabled(true);  
  7.         view.buildDrawingCache();  
  8.         Bitmap b1 = view.getDrawingCache();  
  9.   
  10.         // 获取状态栏高度  
  11.         Rect frame = new Rect();  
  12.         activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  13.         int statusBarHeight = frame.top;  
  14.         Log.i("TAG""" + statusBarHeight);  
  15.   
  16.         // 获取屏幕长和高  
  17.         int width = activity.getWindowManager().getDefaultDisplay().getWidth();  
  18.         int height = activity.getWindowManager().getDefaultDisplay()  
  19.                 .getHeight();  
  20.         // 去掉标题栏  
  21.         // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);  
  22.         Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height  
  23.                 - statusBarHeight);  
  24.         view.destroyDrawingCache();  
  25.         return b;  
  26.     }  
  27.   
  28.     // 保存到sdcard  
  29.     private static void savePic(Bitmap b, String strFileName) {  
  30.           
  31.         FileOutputStream fos = null;  
  32.         try {  
  33.             fos = new FileOutputStream(strFileName);  
  34.             if (null != fos) {  
  35.                 b.compress(Bitmap.CompressFormat.PNG, 90, fos);  
  36.                 fos.flush();  
  37.                 fos.close();  
  38.             }  
  39.         } catch (FileNotFoundException e) {  
  40.             e.printStackTrace();  
  41.         } catch (IOException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  
  45.   
  46.     // 程序入口  
  47.     public static String shoot(Activity a) {  
  48.         String strFileName = "sdcard/" + String.valueOf(System.currentTimeMillis()) + ".png";  
  49.         ScreenShot.savePic(ScreenShot.takeScreenShot(a), strFileName);  
  50.         return strFileName;  
  51.     }  
  52. }  
在需要使用的Activity中调用shoot方法,并使用Intent来分享出去
  1. public class MainActivity extends Activity {  
  2.       
  3.     private Button btn;  
  4.     private String image;  
  5.     private Button btnShare;  
  6.   
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.activity_main);  
  11.         btn = (Button)findViewById(R.id.btn);  
  12.         btn.setOnClickListener(new OnClickListener() {  
  13.               
  14.             @Override  
  15.             public void onClick(View v) {  
  16.                 image = ScreenShot.shoot(MainActivity.this);  
  17.             }  
  18.         });  
  19.         btnShare = (Button) findViewById(R.id.btn_share);  
  20.         btnShare.setOnClickListener(new OnClickListener() {  
  21.               
  22.             @Override  
  23.             public void onClick(View v) {  
  24.                 Intent intent  = new Intent(Intent.ACTION_SEND);  
  25.                 File file = new File(image);  
  26.                 intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));  
  27.                 intent.setType("image/jpeg");  
  28.                 Intent chooser = Intent.createChooser(intent, "Share screen shot");  
  29.                 if(intent.resolveActivity(getPackageManager()) != null){  
  30.                     startActivity(chooser);  
  31.                 }  
  32.             }  
  33.         });  
  34.     }  
  35. }  




2 iOS 

1 先注册通知

 //分享

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(userDidTakeScreenshot:)name:UIApplicationUserDidTakeScreenshotNotificationobject:nil];


/**

 * 截屏分享:截屏响应方法

 */

-(void)userDidTakeScreenshot:(NSNotification*)notification{

    [TCMGoodsSharePopViewclosePopView];

    

    [selfperformSelector:@selector(createShotScreenView)withObject:nilafterDelay:1];

}


- (void)createShotScreenView{

    screenShotView = [TCMGoodsShareScreenShotViewviewFromXIB];

    screenShotView.frame =CGRectMake(0,0, GDeviceScreenWidth,GDeviceScreenHeight);

    UIImage *image = [UIImageimageWithData:[screenShotViewdataWithScreenshotInPNGFormat]];

    //...

    [[UIApplicationsharedApplication].keyWindowaddSubview:screenShotView];

    

    //回调

    [screenShotViewdisplayWithData:imagecodeUrl:theItemInfo.goodsInfo.theShareQRCodeActionBlocks:^(ShareStatusAction statusAction,UIImage *image) {

        NSInteger tag = (statusAction ==ShareStatusAction_weixinTimeLine)?0:1;

        

        [selfshareImage:image Btntag:tag];

        

    } CancelBlock:^{

        [screenShotViewremoveFromSuperview];

    }];

}


#pragma mark - 分享:截屏分享和自定义图片分享

- (void)shareImage:(UIImage *)shareImage Btntag:(NSInteger)tag {

    [[UMSocialManagerdefaultManager]setPlaform:UMSocialPlatformType_WechatSessionappKey:[TCMAppKeyManagertheValueForKeyType:TCM_SDK_Key_Type_AppIdforSDK:TCM_INTEGRATE_SDK_Type_WX]appSecret:[TCMAppKeyManagertheValueForKeyType:TCM_SDK_Key_Type_AppSecretforSDK:TCM_INTEGRATE_SDK_Type_WX]redirectURL:@""];

    

    UMSocialPlatformType  platformType = (tag ==0)? UMSocialPlatformType_WechatTimeLine:UMSocialPlatformType_WechatSession;

    

    //创建分享消息对象

    UMSocialMessageObject *messageObject = [UMSocialMessageObjectmessageObject];

    UMShareImageObject* shareImgObj = [UMShareImageObjectshareObjectWithTitle:@"title"descr:@"descr"thumImage:shareImage];

    shareImgObj.shareImage = shareImage;

    messageObject.shareObject = shareImgObj;

    

    //调用分享接口

    [[UMSocialManagerdefaultManager] shareToPlatform:platformTypemessageObject:messageObjectcurrentViewController:selfcompletion:^(id data,NSError *error) {

        

        //隐藏截图视图

        [screenShotViewremoveFromSuperview];

        [TCMGoodsSharePopViewclosePopView];

        

        if (error) {

//            [CESHelper showPromptHUBWithMsg:@"温馨提示" detailMsg:error.domain timeInterval:1.5];

//            UMSocialLogInfo(@"错误回调 is %@",error.domain);

        }else{

            if ([dataisKindOfClass:[UMSocialShareResponseclass]]) {

                UMSocialShareResponse *resp = data;

                UMSocialLogInfo(@"分享结果消息response message is %@",resp.message);

                UMSocialLogInfo(@"第三方原始返回的数据response originalResponse data is %@",resp.originalResponse);

            }else{

                UMSocialLogInfo(@"response data is %@",data);

            }

        }

    }];

}


截屏的方法如下:

//截取当前屏幕

-(NSData *)dataWithScreenshotInPNGFormat{

    CGSize imageSize =CGSizeZero;

    UIInterfaceOrientation orientation = [UIApplicationsharedApplication].statusBarOrientation;

    if (UIInterfaceOrientationIsPortrait(orientation))

        imageSize = [UIScreenmainScreen].bounds.size;

    else

        imageSize = CGSizeMake([UIScreenmainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);

    UIGraphicsBeginImageContextWithOptions(imageSize,NO, 0);

    CGContextRef context =UIGraphicsGetCurrentContext();

    for (UIWindow *windowin [[UIApplicationsharedApplication] windows])

    {

        CGContextSaveGState(context);

        CGContextTranslateCTM(context, window.center.x, window.center.y);

        CGContextConcatCTM(context, window.transform);

        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);

        if (orientation ==UIInterfaceOrientationLandscapeLeft)

        {

            CGContextRotateCTM(context,M_PI_2);

            CGContextTranslateCTM(context,0, -imageSize.width);

        }

        elseif (orientation ==UIInterfaceOrientationLandscapeRight)

        {

            CGContextRotateCTM(context, -M_PI_2);

            CGContextTranslateCTM(context, -imageSize.height,0);

        } elseif (orientation ==UIInterfaceOrientationPortraitUpsideDown) {

            CGContextRotateCTM(context,M_PI);

            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);

        }

        if ([windowrespondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])

        {

            [window drawViewHierarchyInRect:window.boundsafterScreenUpdates:YES];

        }

        else

        {

            [window.layerrenderInContext:context];

        }

        CGContextRestoreGState(context);

    }

    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    returnUIImagePNGRepresentation(image);

}




//生成的图片

- (UIImage *)snapshotViewFromRect:(CGRect)rect withCapInsets:(UIEdgeInsets)capInsets View:(UIView *)view {

    UIGraphicsBeginImageContextWithOptions(rect.size,NO, [UIScreenmainScreen].scale);

    CGContextRef currentContext =UIGraphicsGetCurrentContext();

    [view.layerrenderInContext:currentContext];

    

    UIImage *snapshotImage =UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    UIImageView *snapshotView = [[UIImageViewalloc] initWithFrame:rect];

    snapshotView.image = [snapshotImageresizableImageWithCapInsets:capInsets];

    

    //    UIGraphicsBeginImageContextWithOptions(CGSizeMake(rect.size.width, rect.size.height + heightWithShuiYin), NO, [UIScreen mainScreen].scale);

    //    UIImageView * snapshotView = [[UIImageView alloc]initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height + heightWithShuiYin)];

    

    return snapshotView.image;

}




三 如果需求是自定义图片分享,先创建视图,然后获取上下文去得到图片分享得到图片的方法如下;

//生成的图片

- (UIImage *)snapshotViewFromRect:(CGRect)rect withCapInsets:(UIEdgeInsets)capInsets {

    UIGraphicsBeginImageContextWithOptions(rect.size,NO, [UIScreenmainScreen].scale);

    CGContextRef currentContext =UIGraphicsGetCurrentContext();

    NSLog(@"width=%.2f,height=%.2f",self.layer.frame.size.width,self.layer.frame.size.height);

    [self.layerrenderInContext:currentContext];

    

    UIImage *snapshotImage =UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    UIImageView *snapshotView = [[UIImageViewalloc] initWithFrame:rect];

    snapshotView.image = [snapshotImageresizableImageWithCapInsets:capInsets];

    

    return snapshotView.image;

}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值