如何向UIButton添加投影?

Chr*_*ost 75 iphone uibutton

我想为UIButton添加一个投影.我试图使用self.layer.shadow*属性.这些属性在UIView中有效,但它们在UIButton中的表现不同.如果我能得到任何指针来绘制投影,我将非常感激.谢谢!

self.layer.cornerRadius = 8.0f;
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;

self.layer.shadowColor = [UIColor greenColor].CGColor;
self.layer.shadowOpacity = 0.8;
self.layer.shadowRadius = 12;
self.layer.shadowOffset = CGSizeMake(12.0f, 12.0f);
Run Code Online (Sandbox Code Playgroud)

fzw*_*zwo 96

问题中只有一个小错误会导致阴影无法显示:masksToBounds:YES也掩盖阴影!这是正确的代码:

self.layer.cornerRadius = 8.0f;
self.layer.masksToBounds = NO;
self.layer.borderWidth = 1.0f;

self.layer.shadowColor = [UIColor greenColor].CGColor;
self.layer.shadowOpacity = 0.8;
self.layer.shadowRadius = 12;
self.layer.shadowOffset = CGSizeMake(12.0f, 12.0f);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这意味着我们无法在没有技巧的情况下屏蔽内容并同时拥有阴影.

记住#import <QuartzCore/QuartzCore.h>.


msg*_*bel 57

如果您使用的是以下,这是一个简单的解决方案UIButton:

#import <QuartzCore/QuartzCore.h>

button.imageView.layer.cornerRadius = 7.0f;
button.layer.shadowRadius = 3.0f;
button.layer.shadowColor = [UIColor blackColor].CGColor;
button.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
button.layer.shadowOpacity = 0.5f;
button.layer.masksToBounds = NO;
Run Code Online (Sandbox Code Playgroud)

刚刚开始工作,并认为值得发布.希望有帮助!

  • 工作完美......即使我不导入“&lt;QuartzCore/QuartzCore.h&gt;”它对我有用......关于我不认识的其他人。 (2认同)

ava*_*nce 38

这是一个不仅创建投影的子类,而且当按下它时按钮会动画下来.

//
//  ShadowButton.h

#import <Foundation/Foundation.h>

@interface ShadowButton : UIButton {
}

@end

//
//  ShadowButton.m

#import "ShadowButton.h"
#import <QuartzCore/QuartzCore.h>

@implementation ShadowButton

-(void)setupView{

    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOpacity = 0.5;
    self.layer.shadowRadius = 1;
    self.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);

}

-(id)initWithFrame:(CGRect)frame{
    if((self = [super initWithFrame:frame])){
        [self setupView];
    }

    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    if((self = [super initWithCoder:aDecoder])){
        [self setupView];
    }

    return self;
}

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.contentEdgeInsets = UIEdgeInsetsMake(1.0,1.0,-1.0,-1.0);
    self.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
    self.layer.shadowOpacity = 0.8;

    [super touchesBegan:touches withEvent:event];

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    self.contentEdgeInsets = UIEdgeInsetsMake(0.0,0.0,0.0,0.0);
    self.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);
    self.layer.shadowOpacity = 0.5;

    [super touchesEnded:touches withEvent:event];

}

@end
Run Code Online (Sandbox Code Playgroud)


bur*_*rki 2

您可以子类化 UIButton 并覆盖 drawRect: 方法并手动添加阴影。这需要做更多的工作,您现在应该了解一些有关quartz 2d 的信息,但结果正是您想要的。否则你可以只添加一个图像,但我更喜欢子类化 UIButton,因为它对于按钮的大小非常灵活,它更通用。