如何绘制平行四边形按钮

时间:2012-09-10 01:06:58

标签: ios uibutton drawing

我需要绘制一个平行四边形的自定义按钮。做这个的最好方式是什么?图像方式(即设置对照的背景图像)不合适。

2 个答案:

答案 0 :(得分:4)

如果您不需要为按钮设置任何图像, Brain89 提供的解决方案就很好。我有背景和内容图像,我需要制作平行四边形按钮而不更改图像。我使用下一个代码:

// 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;
}

答案 1 :(得分:3)

希望这很容易。经过一些谷歌搜索后,我想出了解决方案

<强> 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