How to draw a parallelogram button

2019-04-11 21:24发布

I need to draw a custom button with parallelogram's shape. What is the best way to do this? The image-way (i.e. to set background image for the control) is not suitable.

2条回答
叛逆
2楼-- · 2019-04-11 21:59

The solution offered by Brain89 is good if you don't need to set any image for the button. I have background and content image and I need to make a parallelogram button without changing images. I use the next code:

// Pass 0..1 value to either skewX if you want to compress along the X axis 
// or skewY if you want to compress along the Y axis
- (void)parallelogramButtonWithButton:(UIButton *)button withSkewX:(CGFloat)skewX withSkewY:(CGFloat)skewY {
    CGAffineTransform affineTransform =  CGAffineTransformConcat(CGAffineTransformIdentity, CGAffineTransformMake(1, skewY, skewX, 1, 0, 0));
    button.layer.affineTransform = affineTransform;
}
查看更多
forever°为你锁心
3楼-- · 2019-04-11 22:20

Hopefully, it was very easy. After some googling I came up with the solution

UIParallelogramButton.h

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

@interface UIParallelogramButton : UIButton
{
    CGFloat offset;
}
@property CGFloat offset;
@end

UIParallelogramButton.m

#import "UIParallelogramButton.h"

@implementation UIParallelogramButton
@synthesize offset;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        offset = 0.0F;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    UIBezierPath* maskPath = [UIBezierPath bezierPath];
    [maskPath moveToPoint:CGPointMake(rect.origin.x + offset, rect.origin.y)];
    [maskPath addLineToPoint:CGPointMake(rect.size.width + rect.origin.x, rect.origin.y)];
    [maskPath addLineToPoint:CGPointMake(rect.origin.x + rect.size.width - offset, rect.origin.y + rect.size.height)];
    [maskPath addLineToPoint:CGPointMake(rect.origin.x, rect.origin.y + rect.size.height)];
    [maskPath closePath];
    CAShapeLayer* maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}
@end
查看更多
登录 后发表回答