雑誌で見かけたので、何となくheart typographyを作ってみた。
(XcodeのiOS6 Simulatorで作っています。)
ポイント
・drawRectの中で、ハート形を透明に塗りつぶす
・bezier curveはCGContextAddCurveToPointで書く
サンプルコード
HeartView.h
@interface HeartView : UIView
@property (nonatomic, strong) UIColor *mBackGroundColor;
@end
HeartView.m
#import “HeartView.h”
@implementation HeartView
@synthesize mBackGroundColor;
– (void)drawRect:(CGRect)rect
{
CGSize size = self.bounds.size;
CGContextRef context = UIGraphicsGetCurrentContext();
[self.mBackGroundColor setFill];
CGContextAddRect(context, self.bounds);
CGContextDrawPath(context, kCGPathFill);
[self.mBackGroundColor setFill];
CGContextSetLineWidth(context, 3.0);
CGPoint lCircle = CGPointMake(size.width * 0.7, size.height * 0.3);
CGContextAddArc(context, lCircle.x, lCircle.y, size.width * 0.2, 0, M_PI, YES);
CGPoint rCircle = CGPointMake(size.width * 0.3, size.height * 0.3);
CGContextAddArc(context, rCircle.x, rCircle.y, size.width * 0.2, 0, M_PI, YES);
CGPoint lcp1 = CGPointMake(size.width * 0.05, size.height * 0.6);
CGPoint lcp2 = CGPointMake(size.width * 0.5, size.height * 0.8);
CGContextAddCurveToPoint(context, lcp1.x, lcp1.y, lcp2.x, lcp2.y, size.width * 0.5, size.height * 0.9);
CGPoint rcp1 = CGPointMake(size.width * 0.95, size.height * 0.6);
CGPoint rcp2 = CGPointMake(size.width * 0.5, size.height * 0.8);
CGContextAddCurveToPoint(context, rcp2.x, rcp2.y, rcp1.x, rcp1.y, size.width * 0.9, size.height * 0.3);
CGContextSetBlendMode(context, kCGBlendModeClear);
CGContextDrawPath(context, kCGPathFillStroke);
}
@end
ViewCotnroller.m
#import “ViewController.h”
#import “HeartView.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
CGRect hartRect = CGRectMake(0, 0, 320, 320);
// ハートの中に映す文字
//ランダム310×310のBox内に配置(ハートのFrameに合わせる)
for (int i = 0; i<100; i++) {
UILabel *l = [[UILabel alloc] init];
l.font = [UIFont fontWithName:@”Noteworthy-Bold” size:30];
l.text = @”LOVE”;
l.textColor = [UIColor redColor];
l.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.2];
[l sizeToFit];
float x = arc4random() % (int)hartRect.size.width – 20;
float y = arc4random() % (int)hartRect.size.height – 20;
l.center = CGPointMake(x, y);
[self.view addSubview:l];
[UIView animateWithDuration:2.0f delay:0.1 * i options: UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionBeginFromCurrentState animations:^{
l.center = CGPointMake(150, 150);
} completion:NULL];
}
HeartView *hv = [[HeartView alloc] initWithFrame:hartRect];
hv.backgroundColor = [UIColor clearColor];
hv.mBackGroundColor = [UIColor whiteColor];
[self.view addSubview:hv];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end