如何使setImage UIButton上的UIImage更高一些

时间:2013-07-11 04:34:41

标签: ios objective-c uibutton uiimage

我想要的是在选择UIButton时让UIButton遵守UIView菜单。 选择UIButton后,UINavigation上的黑色方块是UIImage。 我的问题是如何在选中后使UIImage(黑色方块)比UIButton更高?

screenshot

这是我在UIButton Class .m上的代码:

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

        if (self) {
            //...Our red stretchy
            UIImage *redImage = [UIImage imageNamed:@"button_red.png"];
            UIImage *redStretchy = [redImage stretchableImageWithLeftCapWidth:redImage.size.width / 2 topCapHeight:redImage.size.height / 2];

            //...Initialization code
            [self setFrame:frame];
            [self setTitle:TITLE forState:UIControlStateNormal];
            [self setBackgroundImage:redStretchy forState:UIControlStateNormal];
            [[self titleLabel] setFont:[UIFont boldSystemFontOfSize:FONT_SIZE]];
            [[self titleLabel] setShadowOffset:CGSizeMake(FONT_SHADOW_OFFSET, FONT_SHADOW_OFFSET)];

            //...add target
            [self addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
        }

        return self;
    }

这是目标方法:

    //...add target
- (void)actionButton:(id)sender {

    if ([sender isSelected]) {

    } else {

        CGSize buttonSize = CGSizeMake(self.frame.size.width, self.frame.size.height);

        [sender setImage:[self imageButton:buttonSize] forState:UIControlStateSelected];

    }

    if (delegate != nil && [delegate conformsToProtocol:@protocol(ButtonProtocol)]) {
        if ([delegate respondsToSelector:@selector(actionButton:)]) {
            [delegate performSelector:@selector(actionButton:) withObject:sender];
        }
    }

}

这个方法创建UIIMage:

    //...create image button
- (UIImage *)imageButton:(CGSize)size {

    UIGraphicsBeginImageContextWithOptions(size, NO, 0);

    CGContextRef currentContex = UIGraphicsGetCurrentContext();

    CGMutablePathRef path = CGPathCreateMutable();

    CGRect firstRect = CGRectMake(0.0f, 0.0f, 60.f, 30.0f);

    CGPathAddRect(path, NULL, firstRect);

    CGContextAddPath(currentContex, path);

    UIColor *fillColor = [UIColor blackColor];

    CGContextSetFillColorWithColor(currentContex, fillColor.CGColor);

    CGContextDrawPath(currentContex, kCGPathFill);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

0 个答案:

没有答案