我需要绘制平行四边形的形状的自定义按钮。 做这个的最好方式是什么? 图像的方式(即,以设置控制背景图像)是不适合的。
Answer 1:
如果你不需要设置任何图像按钮由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;
}
Answer 2:
我们希望,这是非常容易的。 一些谷歌搜索后,我想出了解决方案
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
文章来源: How to draw a parallelogram button