美文网首页
iOS制作弹幕表情 文字图片

iOS制作弹幕表情 文字图片

作者: 泥孩儿0107 | 来源:发表于2019-04-03 10:47 被阅读0次

gif+文字

+ (NSArray*)addWordToGifWithGifData:(NSData*)imageData withLabel:(UILabel*)label superView:(UIView*)superV{

CGImageSourceRef gifSource = CGImageSourceCreateWithData(CFBridgingRetain(imageData), NULL);/**

    size_tgifCount =CGImageSourceGetCount(gifSource);

    NSMutableArray *frames = [[NSMutableArray alloc]init];

    for(size_ti =0; i< gifCount; i++) {

        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);

        UIImage*image = [UIImageimageWithCGImage:imageRef];

        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, superV.frame.size.width, superV.frame.size.height)];

        imageView.image= image;

        NSData *tempArchive = [NSKeyedArchiver archivedDataWithRootObject:label];

        UILabel *textLabel = (UILabel *)[NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];

        [imageViewaddSubview:textLabel];

        UIGraphicsBeginImageContextWithOptions(superV.frame.size, NO, 0.0);//清晰

        [imageView.layer renderInContext:UIGraphicsGetCurrentContext()];

        UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        [framesaddObject:aimg];

        CGImageRelease(imageRef);

    }

 returnframes;

}

+ (NSString*)creatGifWithImageArrar:(NSArray*)imageArrayM

{

//获取源数据image

    NSMutableArray *imgs = [[NSMutableArray alloc]initWithArray:imageArrayM];

    //图像目标

    CGImageDestinationRef destination;

    //创建输出路径

    NSArray *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString*documentStr = [documentobjectAtIndex:0];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *textDirectory = [documentStr stringByAppendingPathComponent:@"gif"];

    [fileManagercreateDirectoryAtPath:textDirectory withIntermediateDirectories:YES attributes:nil error:nil];

    NSString *path = [textDirectory stringByAppendingPathComponent:@"test101.gif"];

    //创建CFURL对象

    /*

     CFURLCreateWithFileSystemPath(CFAllocatorRef allocator, CFStringRef filePath, CFURLPathStyle pathStyle, Boolean isDirectory)

     allocator : 分配器,通常使用kCFAllocatorDefault

     filePath : 路径

     pathStyle : 路径风格,我们就填写kCFURLPOSIXPathStyle 更多请打问号自己进去帮助看

     isDirectory : 一个布尔值,用于指定是否filePath被当作一个目录路径解决时相对路径组件

     */

    CFURLRef url = CFURLCreateWithFileSystemPath (

                                                  kCFAllocatorDefault,

                                                  (CFStringRef)path,

                                                  kCFURLPOSIXPathStyle,

                                                  false);

    //通过一个url返回图像目标 kUTTypeGIF  CFStringRef

    destination =CGImageDestinationCreateWithURL(url, kUTTypeGIF, imageArrayM.count, NULL);

    //设置gif的信息,播放间隔时间,基本数据,和delay时间

    NSDictionary*frameProperties = [NSDictionary

                                     dictionaryWithObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:0.001f], (NSString *)kCGImagePropertyGIFDelayTime, nil]

                                     forKey:(NSString*)kCGImagePropertyGIFDictionary];

    //设置gif信息

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];

    //

    [dictsetObject:[NSNumber numberWithBool:YES] forKey:(NSString*)kCGImagePropertyGIFHasGlobalColorMap];

    [dictsetObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel];

    [dictsetObject:[NSNumber numberWithInt:8] forKey:(NSString*)kCGImagePropertyDepth];

    [dictsetObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];

    NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:dict

                                                              forKey:(NSString*)kCGImagePropertyGIFDictionary];

    //合成gif

    for(UIImage* dImginimageArrayM)

    {

        CGImageDestinationAddImage(destination, dImg.CGImage, (__bridgeCFDictionaryRef)frameProperties);

    }

    CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifProperties);

    CGImageDestinationFinalize(destination);

    CFRelease(destination);

    returnpath;

}

 图片合成文字

 @param text            文字

 @param fontSize        字体大小

 @param textColor      字体颜色

 @param textFrame      字体位置

 @param image          原始图片

 @param viewFrame      图片所在View的位置

 @return UIImage *

 */

+ (UIImage*)imageWithText:(NSString*)text

                  textFont:(NSInteger)fontSize

                 textColor:(UIColor*)textColor

                 textFrame:(CGRect)textFrame

               originImage:(UIImage*)image

    imageLocationViewFrame:(CGRect)viewFrame

                     label:(UIImageView*)label;

//////////////////////////////////////图片合成文字//////////////////////////////////////////////

+ (UIImage*)imageWithText:(NSString*)text

                  textFont:(NSInteger)fontSize

                 textColor:(UIColor*)textColor

                 textFrame:(CGRect)textFrame

               originImage:(UIImage*)image

    imageLocationViewFrame:(CGRect)viewFrame

                     label:(UIImageView*)label{ 

    if(!text)      {  returnimage;  }

    if(!fontSize)  {  fontSize =17;  }

    if(!textColor) {  textColor = [UIColorblackColor];  }

    if(!image)    {  returnnil;  }

    if(viewFrame.size.height==0|| viewFrame.size.width==0|| textFrame.size.width==0|| textFrame.size.height==0){returnnil;}

    NSString*mark = text;

    CGFloatheight = [marksizeWithPreferWidth:textFrame.size.widthfont:[UIFontsystemFontOfSize:fontSize]].height;// 此分类方法要导入头文件

    if((height + textFrame.origin.y) > viewFrame.size.height) {// 文字高度超出父视图的宽度

        height = viewFrame.size.height- textFrame.origin.y;

    }

    UIImageView *testImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewFrame.size.width, viewFrame.size.height)];

    testImageV.image= image;

    for(inti =0; i < label.subviews.count; i ++) {

        if (![label.subviews[i] isKindOfClass:[UIImageView class]]) {

            NSData *tempArchive = [NSKeyedArchiver archivedDataWithRootObject:label.subviews[i]];

            UILabel *textLabel = (UILabel *)[NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];

            [testImageVaddSubview:textLabel];

        }

    }

//    CGFloat w = image.size.width;

//    CGFloat h = image.size.height;

//    UIGraphicsBeginImageContext(viewFrame.size);//模糊

//    [image drawInRect:CGRectMake(0, 0, viewFrame.size.width, viewFrame.size.height)];

//    NSDictionary *attr = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize], NSForegroundColorAttributeName : textColor };

    //位置显示

//    [mark drawInRect:CGRectMake(textFrame.origin.x, textFrame.origin.y, textFrame.size.width, height) withAttributes:attr];

//    [label drawTextInRect:textFrame];

    UIGraphicsBeginImageContextWithOptions(viewFrame.size, NO, 0.0);//清晰

    [testImageV.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    returnaimg;

}

弹幕表情

-(void)makeGif {

    [MBProgressHUDshowMessag:@"正在生成"toView:self.view];

    __blockintflagkkk =1;

    NSMutableArray *arrpoiu = [NSMutableArray arrayWithCapacity:0];

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {

        //        将定时器时间内每隔.1(截图频率,自己可以控制)的屏幕截图储存起来,保存成功后进行下一张存放

        flagkkk +=1;

        if(flagkkk ==10) {

            [timerinvalidate];

            timer =nil;

            flagkkk =1;

            [selfcreategif:arrpoiu];

            NSData *data1lll = [NSData dataWithContentsOfFile:_pathUrl];

            //        保存到本地相册

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                NSData*datapooo = data1lll;

                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

                    [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:datapooo options:nil];

                }completionHandler:^(BOOLsuccess,NSError*_Nullableerror) {

                    dispatch_async(dispatch_get_main_queue(), ^{

                        [MBProgressHUD hideHUDForView:self.view animated:YES];

                        if(success) {

                            [MBProgressHUDshowSuccess:@"保存成功"toView:self.view];

                        }else{

                            [MBProgressHUDshowError:@"保存失败,请重试"toView:self.view];

                        }

                    });

                }];

            });

        }

        UIImage *imageppoj = [screenShotToll shotInView:self.tscroitleLabel];

        [arrpoiuaddObject:imageppoj];

    }];

    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

}

-(void)creategif:(NSArray*)arr

{

    //图像目标

    CGImageDestinationRef destination;

    NSString*path ;

    //创建输出路径

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSArray *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString*documentStr = [documentobjectAtIndex:0];

    NSString *textDirectory = [documentStr stringByAppendingPathComponent:@"gif"];

    [fileManagercreateDirectoryAtPath:textDirectory withIntermediateDirectories:YES attributes:nil error:nil];

    NSString *gifName = [NSString stringWithFormat:@"yangyang.gif"];

    path = [textDirectorystringByAppendingPathComponent:gifName];

    CFURLRef url = CFURLCreateWithFileSystemPath (

                                                  kCFAllocatorDefault,

                                                  (CFStringRef)path,

                                                  kCFURLPOSIXPathStyle,

                                                  false);

    //通过一个url返回图像目标

    destination =CGImageDestinationCreateWithURL(url, kUTTypeGIF, arr.count, NULL);

    //设置gif的信息,播放间隔时间,基本数据,和delay时间

    NSDictionary*frameProperties = [NSDictionary

                                     dictionaryWithObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:0.3], (NSString *)kCGImagePropertyGIFDelayTime, nil]

                                     forKey:(NSString*)kCGImagePropertyGIFDictionary];

    //设置gif信息

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];

    [dictsetObject:[NSNumber numberWithBool:YES] forKey:(NSString*)kCGImagePropertyGIFHasGlobalColorMap];

    [dictsetObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel];

    [dictsetObject:[NSNumber numberWithInt:8] forKey:(NSString*)kCGImagePropertyDepth];

    [dictsetObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];

    NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:dict

                                                              forKey:(NSString*)kCGImagePropertyGIFDictionary];

    //合成gif

    for(UIImage* dImginarr)

    {

        CGImageDestinationAddImage(destination, dImg.CGImage, (__bridgeCFDictionaryRef)frameProperties);

    }

    CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifProperties);

    CGImageDestinationFinalize(destination);

    CFRelease(destination);

    _pathUrl= path;

}

+ (UIImage*)shotInView:(UIView*)view

{

    UIGraphicsBeginImageContext(view.bounds.size);

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    returnimage;

}

文字图片

UIGraphicsBeginImageContext(self.tscroitleLabel.frame.size);

    [self.tscroitleLabel drawViewHierarchyInRect:self.tscroitleLabel.bounds afterScreenUpdates:NO];

    UIImage* image =  UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

相关文章

网友评论

      本文标题:iOS制作弹幕表情 文字图片

      本文链接:https://www.haomeiwen.com/subject/wmvpbqtx.html