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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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;
}
回答2:
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