如何模糊UILabel文本

时间:2015-05-18 12:20:04

标签: ios uilabel

我试图模糊UILabel的文字而没有图像模糊方法。我发现了许多解决方案,但最大的是图像。我尝试了图层的阴影功能,但这没有用。

1 个答案:

答案 0 :(得分:4)

您可以创建一个UILabel的子类来创建模糊效果。

这是一个锅炉模板:

BlurredUILabel.h

#import <UIKit/UIKit.h>

@interface BlurredUILabel : UILabel

@property (nonatomic, readwrite) IBInspectable CGFloat blurRadius;

@end

BlurredUILabel.m

#import "BlurredUILabel.h"

@implementation BlurredUILabel

- (void)setText:(NSString *)text {
    super.text = text;
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CIFilter *blurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [blurFilter setDefaults];

    CIImage *imageToBlur = [CIImage imageWithCGImage:image.CGImage];
    [blurFilter setValue:imageToBlur forKey:kCIInputImageKey];
    [blurFilter setValue:@(self.blurRadius) forKey:@"inputRadius"];

    CIImage *outputImage = blurFilter.outputImage;
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];

    [self.layer setContents:(__bridge id)cgimg];
    CGImageRelease(cgimg);
}

@end

你会像这样使用它:

#import "TestViewController.h"
#import "BlurredUILabel.h"

@interface TestViewController ()

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    BlurredUILabel *label = [[BlurredUILabel alloc] initWithFrame:CGRectMake(50, 50, 300, 50)];
    label.blurRadius = 2.0;
    label.backgroundColor = [UIColor redColor];
    label.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:35];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"HELLO";
    [self.view addSubview:label];

    label.blurRadius = 1.5;
    [label performSelector:@selector(setText:) withObject:@"Test new string" afterDelay:2];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end