文章目录
目的
制作一个带阴影的Button
替换NSButton
背景色以及绘制圆角和阴影。
设置图片的话就还要考虑阴影问题,颜色还要考虑是否和图片的一致,复用性也不高。
起初想使用drawRect:
直接绘制,但是会遮罩文本和无法显示圆角,使用其layer
层的现有接口似乎更简单快捷,所以着手修改其layer
层来实现了。
CustomButton
NSView
都有一个wantsUpdateLayer
,默认返回NO
时视图会默认调用drawRect
方法,当返回为YES
时,会调用- (void)updateLayer
方法
- (BOOL)wantsUpdateLayer {
return YES;
}
- (void)updateLayer {
//changed to the width or height of a single source pixel centered at the specified location.
self.layer.contentsCenter = CGRectMake(0.5, 0.5, 0, 0);
//setImage
self.layer.backgroundColor = _backgroundColor.CGColor;
self.layer.cornerRadius = _cornerRadius;
self.layer.shadowColor = _backgroundColor.CGColor;
if (!CGSizeEqualToSize(CGSizeZero, _shadowOffset)) {
self.layer.masksToBounds = NO;
self.layer.shadowOffset = CGSizeMake(1, 2);
self.layer.shadowRadius = 6.f;
self.layer.shadowOpacity = 1;
}
}
代码
CustomButton.h
//
// CustomButton.h
// Training
//
// Created by gensee on 2020/1/3