文字加描邊
阿新 • • 發佈:2021-10-14
1、自定義UILabel
-
GC_Label.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface GC_Label : UILabel
// 設定文字描邊:預設不描邊,設定了描邊顏色才會描邊
/** 描邊顏色 */
@property(nonatomic, strong) UIColor *stroke_color;
/** 描邊寬度,預設為1 */
@property(nonatomic, assign) CGFloat stroke_width;
@end
NS_ASSUME_NONNULL_END
-
GC_Label.m
#import "GC_Label.h" @implementation GC_Label - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = Clear_Color; self.stroke_width = 1; } return self; } - (void)drawTextInRect:(CGRect)rect { if (self.stroke_color) { UIColor *temp_color = self.textColor; CGContextRef context = UIGraphicsGetCurrentContext(); // 設定描邊寬度 CGContextSetLineWidth(context, self.stroke_width); CGContextSetLineJoin(context, kCGLineJoinRound); CGContextSetTextDrawingMode(context, kCGTextStroke); // 描邊顏色 self.textColor = self.stroke_color; [super drawTextInRect:rect]; // 文字顏色 self.textColor = temp_color; CGContextSetTextDrawingMode(context, kCGTextFill); [super drawTextInRect:rect]; } else { [super drawTextInRect:rect]; } } @end
2、使用與效果
-
使用
_title_tv = [[GC_Label alloc] init];
_title_tv.textAlignment = NSTextAlignmentCenter;
_title_tv.textColor = [UIColor redColor];
_title_tv.stroke_color = [UIColor darkGrayColor];
_title_tv.stroke_width = 5;
_title_tv.text = @"溫度26℃";
-
效果
作者: CH520 出處: 部落格園資源分享中心