我想在iOS应用中绘制纹理按钮。我不会使用Photoshop而不是CoreGraphics因为我想要一个适用于不同大小的按钮的通用解决方案。它的基本原理是什么?我需要什么技术?
我的第一步是将UIButton子类化,但是如何添加ie斜角效果呢?
答案 0 :(得分:3)
最好的方法是将按钮类子类化(您的新类必须从UIButton继承)。通过这样做,您可以为您的按钮提供一些自定义的详细信息..下面是一个示例..
//interface of custom button class
@interface myButton : UIButton
{
int orderNo;
CAGradientLayer *gradientLayer;
CALayer *wrapperLayer;
CGColorRef _borderColor;
}
@property (assign) int orderNo;
@property (nonatomic) CGColorRef _borderColor;
@property (nonatomic, retain) CALayer *wrapperLayer;
@property (nonatomic, retain) CAGradientLayer *gradientLayer;
- (void)setBorderColor:(CGColorRef)color;
- (void)setCornerRadius:(float)radius;
实施..
#import "Button.h"
@implementation Button
@synthesize orderNo,wrapperLayer,_borderColor,gradientLayer;
- (id)initWithFrame:(CGRect)frame
{if ((self = [super initWithFrame:frame])) {
CGFloat radius = self.bounds.size.width / 2;
CGFloat borderWidth = self.bounds.size.width / 10;
self.layer.backgroundColor = [[UIColor blackColor] CGColor];
self.layer.borderColor = [[UIColor whiteColor] CGColor];
self.layer.borderWidth = borderWidth;
self.layer.cornerRadius = radius;
if ([self.layer respondsToSelector:@selector(setShadowOffset:)])
self.layer.shadowOffset = CGSizeMake(0.25, 0.25);
if ([self.layer respondsToSelector:@selector(setShadowColor:)])
self.layer.shadowColor = [[UIColor blackColor] CGColor];
if ([self.layer respondsToSelector:@selector(setShadowRadius:)])
self.layer.shadowRadius = borderWidth;
if ([self.layer respondsToSelector:@selector(setShadowOpacity:)])
self.layer.shadowOpacity = 0.75;
[self setNeedsDisplay];
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetShouldAntialias(ctx, true);
CGFloat xsize = self.bounds.size.width / 6;
CGFloat borderWidth = self.bounds.size.width / 10;
CGContextSaveGState(ctx);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineWidth(ctx, borderWidth);
CGContextSetStrokeColorWithColor(ctx, [[UIColor whiteColor] CGColor]);
CGFloat width = self.bounds.size.width;
CGPoint start1 = CGPointMake(width / 2 - xsize, width / 2 - xsize);
CGPoint end1 = CGPointMake(width / 2 + xsize, width / 2 + xsize);
CGPoint start2 = CGPointMake(width / 2 + xsize, width / 2 - xsize);
CGPoint end2 = CGPointMake(width / 2 - xsize, width / 2 + xsize);
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, start1.x, start1.y);
CGContextAddLineToPoint(ctx, end1.x, end1.y);
CGContextStrokePath(ctx);
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, start2.x, start2.y);
CGContextAddLineToPoint(ctx, end2.x, end2.y);
CGContextStrokePath(ctx);
CGContextRestoreGState(ctx);
}
- (void)setBorderColor:(CGColorRef)color
{
[[self layer] setBorderColor:color];
[[self layer] setNeedsDisplay];
}
- (void)setCornerRadius:(float)radius
{
[[self layer] setCornerRadius:radius];
// and get the wrapper for the gradient layer too
[wrapperLayer setCornerRadius:radius];
}
@end