zoukankan      html  css  js  c++  java
  • 自己定义UIView以实现自绘

    有时候我们须要自绘uiview以实现自己的需求,比方依据坐标点绘制出连续的曲线(股票走势图),就须要自绘uiview了。

    原理:继承uiview类(customView),并实现custom view的drawRect即可。

    首先看一下效果图:


    代码例如以下:

    // .h

    #import <UIKit/UIKit.h>


    @interface CustomView : UIView

    @end


    //.m

    #import "CustomView.h"


    @implementation CustomView


    -(id)initWithFrame:(CGRect)frame{

        //重写initWithFrame时,不要忘了以下一句

        self = [superinitWithFrame:frame];

        

        if (self) {

            self.backgroundColor = [UIColorwhiteColor];

        }

        

        return self;

    }


    //重写drawRect方法(不须要调用)。绘制想要的图像

    -(void)drawRect:(CGRect)rect{

     

        CGContextRef context = UIGraphicsGetCurrentContext();//context:一块内存区域。将它看做当前view的画布即可了。


        NSDictionary *attribute = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize: 15.0f], NSFontAttributeName, [UIColor redColor],  NSForegroundColorAttributeName, nil];

        [@"股市走势图" drawInRect:CGRectMake(100, 200, 80, 20) withAttributes:attribute] ;//绘画标题

        

        //曲线

        CGContextMoveToPoint(context, 10, 400);

        CGContextAddLineToPoint(context, 100, 450);

        CGContextAddLineToPoint(context, 150, 400);

        CGContextAddLineToPoint(context, 200, 450);

        //CGContextStrokePath(context);

        

        //三角形

        CGContextMoveToPoint(context, 20, 100);

        CGContextAddLineToPoint(context, 40, 300);

        CGContextAddLineToPoint(context, 200, 200);

        CGContextClosePath(context);

        CGContextStrokePath(context);

        //CGContextFillPath(context);

        

        //矩形

        CGContextAddRect(context, CGRectMake(20, 20, 100, 50));

        [[UIColor colorWithRed:1 green:0 blue:0 alpha:1] set];

        //CGContextStrokePath(context);//空心

        CGContextFillPath(context);//实心

        

         //

        CGContextAddArc(context, 150, 150, 100, 0, 2*M_PI, 0);

        CGContextStrokePath(context);

    }


    @end


    然后在须要用到该view的view controller的

    viewDidLoad下加入西;以下代码就能够了!

    CustomView *view = [[CustomView alloc]  initWithFrame:[UIScreen mainScreen].bounds];

    [self.view addSubview view];


  • 相关阅读:
    安卓组件service
    安卓组件-BroadcastReceiver
    【bug】java.lang.NoSuchMethodError: android.widget.TextView.setBackground
    【转】安卓毛玻璃效果
    INSTALL_FAILED_UPDATE_INCOMPATIBLE
    安卓 异步线程更新Ui
    OC语言-03-OC语言-三大特性
    OC语言-02-OC语言-基础知识
    OC语言-01-面向过程与面向对象思想
    C语言-07-预处理、typedef、static和extern
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/8372219.html
Copyright © 2011-2022 走看看