如何模糊UILabel文本[英] How to blur UILabel text

本文是小编为大家收集整理的关于如何模糊UILabel文本的处理方法,想解了如何模糊UILabel文本的问题怎么解决?如何模糊UILabel文本问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我正在尝试在不使用图像模糊方法的情况下模糊 UILabel 的文本.我找到了很多解决方案,但图像最多.我尝试了图层的阴影功能,但这没有帮助.

推荐答案

你可以只创建一个 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

本文地址:https://www.itbaoku.cn/post/924618.html