-
實(shí)例:繪制文字與圖片到視圖中
效果圖.png
注意:
- 要自定義視圖,然后重寫drawRect:方法,進(jìn)行重繪,與Quartz2D一樣乎婿,都要重寫該方法進(jìn)行重繪
實(shí)現(xiàn):
- 1.自定義視圖,重寫drawRect:方法進(jìn)行重繪
// .h文件
#import <UIKit/UIKit.h>
@interface DrawTextView : UIView
@end
// .m 實(shí)現(xiàn)文件
#import "DrawTextView.h"
@implementation DrawTextView
/**
* 重寫該方法街佑,進(jìn)行視圖重繪
*/
- (void)drawRect:(CGRect)rect {
// Drawing code
/**
* 富文本
*/
// 向視圖上畫文字
NSString *text = @"畫文字";
NSDictionary *dict = @{
NSFontAttributeName : [UIFont systemFontOfSize:50 ],
NSBackgroundColorAttributeName : [UIColor redColor],
NSStrokeColorAttributeName : [UIColor greenColor],
NSStrokeWidthAttributeName : @"3"
};
[text drawAtPoint:CGPointMake(0, 0) withAttributes:dict];
// 向視圖上繪制圖片
[self drawImage:CGRectMake(100, 100, 80, 80)];
}
/**
* 向視圖中繪制圖片
*
* @param rect 繪制圖片的位置與尺寸
*/
- (void)drawImage:(CGRect) rect{
UIImage *image = [UIImage imageNamed:@"Snip20150804_2"];
// [image drawAsPatternInRect:rect];
// [image drawAtPoint:CGPointMake(0, 0)];
[image drawInRect:rect];
}
/**
* 向視圖上畫文字
*/
- (void)drawText{
NSString *text = @"呵呵";
[text drawInRect:self.bounds withAttributes:nil];
[text drawAtPoint:CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5) withAttributes:nil];
}
@end
- 2.在控制器.m文件中谢翎,添加自定義DrawTextView控件,即可顯示以上效果