Android 使用svg構(gòu)造交互式中國地圖

1. 概念

什么是svg

即Scalable Vector Graphics 可伸縮矢量圖形
SVG的W3C的解釋: http://www.w3school.com.cn/svg/svg_intro.asp
什么是矢量圖像,什么是位圖圖像?
1、矢量圖像:SVG是W3C 推出的一種開放標(biāo)準(zhǔn)的文本式矢量圖形描述語言,他是基于XML的、專門為網(wǎng)絡(luò)而設(shè)計的圖像格式,
SVG是一種采用XML來描述二維圖形的語言,所以它可以直接打開xml文件來修改和編輯。
2、位圖圖像:位圖圖像的存儲單位是圖像上每一點的像素值,因而文件會比較大,像GIF、JPEG、PNG等都是位圖圖像格式。

Vector

在Android中指的是Vector Drawable,也就是Android中的矢量圖,
可以說Vector就是Android中的SVG實現(xiàn)(并不是支持全部的SVG語法,現(xiàn)已支持的完全足夠用了)

    補(bǔ)充:Vector圖像剛發(fā)布的時候,是只支持Android 5.0+的,自從AppCompat 23.2之后,Vector可以使用于Android 2.1以上的所有系統(tǒng),
            只需要引用com.android.support:appcompat-v7:23.2.0以上的版本就可以了。(所謂的兼容也是個坑爹的兼容,即低版本非真實使用SVG,而是生成PNG圖片)

2.Vector Drawable

Android 5.0發(fā)布的時候,Google提供了Vector的支持,即:Vector Drawable類。
Vector Drawable相對于普通的Drawable來說,有以下幾個好處:
(1)Vector圖像可以自動進(jìn)行適配,不需要通過分辨率來設(shè)置不同的圖片。
(2)Vector圖像可以大幅減少圖像的體積,同樣一張圖,用Vector來實現(xiàn),可能只有PNG的幾十分之一。
(3)使用簡單,很多設(shè)計工具,都可以直接導(dǎo)出SVG圖像,從而轉(zhuǎn)換成Vector圖像 功能強(qiáng)大。
(4)不用寫很多代碼就可以實現(xiàn)非常復(fù)雜的動畫 成熟、穩(wěn)定,前端已經(jīng)非常廣泛的進(jìn)行使用了。

    1) Vector 語法簡介
        通過使用它的Path標(biāo)簽,幾乎可以實現(xiàn)SVG中的其它所有標(biāo)簽,雖然可能會復(fù)雜一點,
        但這些東西都是可以通過工具來完成的,所以,不用擔(dān)心寫起來會很復(fù)雜。
        (1)Path指令解析如下所示:
            M = moveto(M X,Y) :將畫筆移動到指定的坐標(biāo)位置,相當(dāng)于 android Path 里的moveTo()
            L = lineto(L X,Y) :畫直線到指定的坐標(biāo)位置,相當(dāng)于 android Path 里的lineTo()
            H = horizontal lineto(H X):畫水平線到指定的X坐標(biāo)位置 
            V = vertical lineto(V Y):畫垂直線到指定的Y坐標(biāo)位置 
            C = curveto(C X1,Y1,X2,Y2,ENDX,ENDY):三次貝賽曲線 
            S = smooth curveto(S X2,Y2,ENDX,ENDY) 同樣三次貝塞爾曲線,更平滑 
            Q = quadratic Belzier curve(Q X,Y,ENDX,ENDY):二次貝賽曲線 
            T = smooth quadratic Belzier curveto(T ENDX,ENDY):映射 同樣二次貝塞爾曲線,更平滑 
            A = elliptical Arc(A RX,RY,XROTATION,FLAG1,FLAG2,X,Y):弧線 ,相當(dāng)于arcTo()
            Z = closepath():關(guān)閉路徑(會自動繪制鏈接起點和終點)

            注意,’M’處理時,只是移動了畫筆, 沒有畫任何東西。

    注意:1.關(guān)于這些語法,開發(fā)者不需要全部精通,而是能夠看懂即可,這些path標(biāo)簽及數(shù)據(jù)生成都可以交給工具來實現(xiàn)。
        (一般美工來幫你搞定!PS、Illustrator等等都支持導(dǎo)出SVG圖片)

            2.程序員:沒必要去學(xué)習(xí)使用這些設(shè)計工具,開發(fā)者可以利用一些工具,自己轉(zhuǎn)換一些比較基礎(chǔ)的圖像,
                如:http://inloop.github.io/svg2android/ 
            3.還可以使用SVG的編輯器來進(jìn)行SVG圖像的編寫,例如:http://editor.method.ac/
            (絕配!可以先用http://editor.method.ac/ 生成SVG圖片,然后用http://inloop.github.io/svg2android/ 生成 VectorDrawable xml代碼)
            4.使用AndroidStudio插件完成SVG添加(Vector Asset Studio)
                詳細(xì):http://www.itdecent.cn/p/d6c39f2dd5e7
                AS會自動生成兼容性圖片(高版本會生成xxx.xml的SVG圖片;低版本會自動生成xxx.png圖片)
            5.有些網(wǎng)站可以找到SVG資源
                SVG下載地址: http://www.shejidaren.com/8000-flat-icons.html
                              http://www.flaticon.com/
                              
                              http://www.iconfont.cn/plus --- 阿里巴巴
                              
                圖片轉(zhuǎn)成SVG https://vectormagic.com/

兼容問題,5.0以上的可以直接用:

一、兼容5.0以下的版本

1、使用Android Studio 2.2以上的版本,gradle版本在2.0以上,準(zhǔn)備步驟

1.1、添加

· defaultConfig {
vectorDrawables.useSupportLibrary = true

}
1.2、添加
compile 'com.android.support:appcompat-v7:25.3.1' //需要是23.2 版本以上的

1.3、Activity需要繼承與AppCompatActivity

1.4、布局文件當(dāng)中添加
    xmlns:app="http://schemas.android.com/apk/res-auto"


2、使用在Actvity前面添加一個flag設(shè)置
    
    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

2.1 ImageView/ImageButton
    XML app:srcCompat
    代碼里面使用無區(qū)別

2.2 Button 不支持app:srcCompat
    Xml 使用在Button的selector

2.3 RadioButton 直接使用

2.4 textview的drawable  直接使用



2.5 使用的動態(tài)Vector Drawable
    主要是不能直接修改 pathData
    不能使用自定義interpolator

SVG使用

map.gif

實現(xiàn)思路:
第一步 下載含有中國地圖的 SVG
第二步 用http://inloop.github.io/svg2android/ 網(wǎng)站 將svg資源轉(zhuǎn)換成相應(yīng)的 Android代碼
第三步 利用Xml解析SVG的代碼 封裝成javaBean 最重要的得到Path
第四步 重寫OnDraw方法 利用Path繪制中國地圖
第五步 重寫OnTouchEvent方法,記錄手指觸摸位置,判斷這個位置是否坐落在某個省份上。代碼

  public class MyMapView extends View {
    private Paint mPaint;
    private Context context;
    private int[] colors = new int[]{Color.RED, Color.GREEN, Color.YELLOW, Color.GREEN};
    private ArrayList<ProvinceBean> itemList = new ArrayList<>();
    private ProvinceBean selectItem;
    private GestureDetectorCompat gestureDetectorCompat;

    public MyMapView(Context context) {
        this(context, null);
    }

    public MyMapView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        //準(zhǔn)備畫筆
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        this.context = context;
        thread.start();

        //手勢處理類
        gestureDetectorCompat = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                Log.d("event   ", e.getAction() + "");
                handlerTouch(e.getX(), e.getY());
                return true;
            }
        });

    }

    private void handlerTouch(float x, float y) {
        if (itemList != null) {
            for (ProvinceBean item : itemList) {
                if (item.isTouch((int) (x / 1.4), (int) (y / 1.4))) {
                    selectItem = item;
                    postInvalidate();
                    break;
                }
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetectorCompat.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        canvas.scale(1.4f, 1.4f);
        for (int i = 0; i < itemList.size(); i++) {
            if (selectItem != itemList.get(i)) {
                itemList.get(i).draw(mPaint, canvas, false);
            }
        }
        if (selectItem != null) {
            selectItem.draw(mPaint, canvas, true);
        }
        canvas.restore();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                postInvalidate();
            }
        }
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            //dom解析xml
            InputStream inputStream = context.getResources().openRawResource(R.raw.chinahigh);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = null;
            try {
                builder = factory.newDocumentBuilder();
                Document document = builder.parse(inputStream);//解析輸入流
                Element rootElement = document.getDocumentElement();
                NodeList items = rootElement.getElementsByTagName("path");
                Log.d("MyMapView:", "集合大小=" + items.getLength());
                for (int i = 0; i < items.getLength(); i++) {
                    int colorsIndex = i % 4;
                    Element element = (Element) items.item(i);
                    String pathData = element.getAttribute("android:pathData");
                    Path path = PathParser.createPathFromPathData(pathData);
                    ProvinceBean provinceBean = new ProvinceBean(path);
                    provinceBean.setColor(colors[colorsIndex]);
                    itemList.add(provinceBean);
                }
                handler.sendEmptyMessage(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
public class ProvinceBean {
    private Path path;
    private int color;

    public ProvinceBean(Path path) {
        this.path = path;
    }

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
    }

    /**
     * 繪制省份
     *
     * @param paint
     * @param canvas
     * @param isSelected 是否被選中
     */
    public void draw(Paint paint, Canvas canvas, boolean isSelected) {
        if (isSelected){
            //繪制點擊后的背景
            paint.setStrokeWidth(2);
            paint.setColor(color);
            paint.setStyle(Paint.Style.FILL);
            //添加陰影
            paint.setShadowLayer(8,0,0,Color.BLACK);
            canvas.drawPath(path,paint);
            //繪制背景
            paint.clearShadowLayer();
            paint.setStrokeWidth(2);
            paint.setColor(color);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawPath(path,paint);

        }else{
            //繪制背景
            paint.setStrokeWidth(2);
            paint.clearShadowLayer();
            paint.setColor(color);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawPath(path,paint);
            //繪制邊界線
            paint.setStrokeWidth(1);
            paint.setColor(Color.GRAY);
            paint.setStyle(Paint.Style.STROKE);
            canvas.drawPath(path,paint);

        }

    }

    //觸摸點是否在這個省的path內(nèi)
    public boolean isTouch(int x, int y) {
        //構(gòu)造一個矩形對象
        RectF rectF=new RectF();
        //返回路徑控制點的計算邊界保存到rectF
        path.computeBounds(rectF,true);
        //構(gòu)造一個區(qū)域?qū)ο?        Region region=new Region();
        //給區(qū)賦值
        region.setPath(path,new Region((int)rectF.left,(int)rectF.top,(int)rectF.right,(int)rectF.bottom));
        return region.contains(x,y);
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容