利用drawinrect在control中畫入圖片和文字

//

//  BtnControl.m

//  ZCar

//

//  Created by imac on 15/10/4.

//  Copyright (c) 2015 imac. All rights reserved.

//


#import "BtnControl.h"


@implementation BtnControl

-(instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        

        self.layer.borderColor = [UIColor lightGrayColor].CGColor;

        self.layer.borderWidth = 1;

        self.backgroundColor = [UIColor whiteColor];

        

    }

    return self;

}


-(void)setNameWithTitle:(NSString *)nameWithTitle

{

    if (_nameWithTitle != nameWithTitle) {

        _nameWithTitle = nameWithTitle;

        [self setNeedsDisplay];

    }

}

- (void)setImgName:(NSString *)imgName

{

    if (_imgName != imgName) {

        _imgName = imgName;

        [self setNeedsDisplay];

    }

}

- (void)setDic:(NSDictionary *)dic

{

    if (_dic != dic) {

        _dic = dic;

        [self setNeedsDisplay];

    }

}

- (void)drawRect:(CGRect)rect

{

    [super drawRect:rect];

    [self drawWithText:_nameWithTitle ImgName:_imgName titleColor:_dic];

}

- (void)drawWithText:(NSString *)title ImgName:(NSString *)imgName titleColor:(NSDictionary *)dic{

    

    UIImage *img = [UIImage p_w_picpathNamed:imgName];

    [img drawInRect:CGRectMake(self.width - 27, self.height - 12, 25, 10)];

    int i = [self convertToInt:title];

    float width = (self.width - i * 12) / 2;

    [title drawInRect:CGRectMake(width, 10, self.width, self.height) withAttributes:dic];

}

-  (int)convertToInt:(NSString*)strtemp {

    

    int strlength = 0;

    

    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];

    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {

        if (*p) {

            p++;

            strlength ++;

        }

        else {

            p ++;

        }

    }

    return (strlength + 1) / 2;

    

}

@end



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章