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
,如果你不通過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;
}