佳为好友

原:为UIButton加入重叠背景图片

创建:120630
为UIButton加入背景图片很容易,但是如果背景图片是以重叠方式加入的,而非一个完整的图片,则比较困难。
思路是建立一个sublayer加入到button的layer上。该sublayer负责加入背景图片。
同时,layer的borderColor设定边框,sublayer的borderColor设定内部边框。
同时要注意:初始的button的宽高一定要很长,否则无法正确加载图片和边框。
同时,textLabel一定要重新调整到最前方,否则,无法在显示文字。

@implementation UIButton (ContextualAction)


- (void)setContextualActionStyle

{

    UIButton *button = self;

    CGRect oldFrame = button.frame;

    button.frame = CGRectMake(0.0f, 0.0f, 1000.0f, 1000.0f); // width and height must be bigger enough.

    

    

    CALayer *layer = button.layer;

    layer.cornerRadius = 5.0f;

    layer.masksToBounds = YES;

    layer.borderWidth = 1.0f;

    layer.borderColor = [UIColor lightGrayColor].CGColor;

    

    CALayer *shineLayer = [CALayer layer];

    shineLayer.frame = button.layer.bounds;

    UIImage *lightGrayBackgroundImage = [UIImage imageNamed:@"texture_light.png"];    

    shineLayer.backgroundColor =  [UIColor colorWithPatternImage:lightGrayBackgroundImage].CGColor;

    shineLayer.borderWidth = 2.0f; // 1.0f px will be cover by layer.border.

    shineLayer.borderColor = [UIColor whiteColor].CGColor;

    [button.layer addSublayer:shineLayer];

    

    button.titleLabel.textAlignment = UITextAlignmentCenter;

    button.titleLabel.font = [UIFont boldSystemFontOfSize:10];

    [button setTitleColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0fblue:102.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];

    [button setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal];

    button.titleLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);

    [button bringSubviewToFront:button.titleLabel]; // must add. otherwise the title won't show.


    button.frame = oldFrame;

}



@end

+++++

posted on 2012-12-29 10:51 佳为好友 阅读(511) 评论(0)  编辑 收藏 引用 所属分类: UI


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2012年12月>
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

留言簿(1)

随笔分类

搜索

最新评论

评论排行榜