1. 概念
什么是svg
即Scalable Vector Graphics 可伸縮矢量圖形
SVG的W3C的解釋: http://www.w3school.com.cn/svg/svg_intro.asp
什么是矢量圖像叹话,什么是位圖圖像蕴忆?
1、矢量圖像:SVG是W3C 推出的一種開(kāi)放標(biāo)準(zhǔn)的文本式矢量圖形描述語(yǔ)言,他是基于XML的惕耕、專門為網(wǎng)絡(luò)而設(shè)計(jì)的圖像格式躏嚎,
SVG是一種采用XML來(lái)描述二維圖形的語(yǔ)言,所以它可以直接打開(kāi)xml文件來(lái)修改和編輯菩貌。
2卢佣、位圖圖像:位圖圖像的存儲(chǔ)單位是圖像上每一點(diǎn)的像素值,因而文件會(huì)比較大箭阶,像GIF虚茶、JPEG、PNG等都是位圖圖像格式仇参。
Vector
在Android中指的是Vector Drawable嘹叫,也就是Android中的矢量圖,
可以說(shuō)Vector就是Android中的SVG實(shí)現(xiàn)(并不是支持全部的SVG語(yǔ)法,現(xiàn)已支持的完全足夠用了)
補(bǔ)充:Vector圖像剛發(fā)布的時(shí)候诈乒,是只支持Android 5.0+的罩扇,自從AppCompat 23.2之后,Vector可以使用于Android 2.1以上的所有系統(tǒng),
只需要引用com.android.support:appcompat-v7:23.2.0以上的版本就可以了喂饥。(所謂的兼容也是個(gè)坑爹的兼容消约,即低版本非真實(shí)使用SVG,而是生成PNG圖片)
2.Vector Drawable
Android 5.0發(fā)布的時(shí)候,Google提供了Vector的支持员帮,即:Vector Drawable類或粮。
Vector Drawable相對(duì)于普通的Drawable來(lái)說(shuō),有以下幾個(gè)好處:
(1)Vector圖像可以自動(dòng)進(jìn)行適配捞高,不需要通過(guò)分辨率來(lái)設(shè)置不同的圖片氯材。
(2)Vector圖像可以大幅減少圖像的體積,同樣一張圖硝岗,用Vector來(lái)實(shí)現(xiàn)氢哮,可能只有PNG的幾十分之一。
(3)使用簡(jiǎn)單辈讶,很多設(shè)計(jì)工具命浴,都可以直接導(dǎo)出SVG圖像,從而轉(zhuǎn)換成Vector圖像 功能強(qiáng)大贱除。
(4)不用寫(xiě)很多代碼就可以實(shí)現(xiàn)非常復(fù)雜的動(dòng)畫(huà) 成熟生闲、穩(wěn)定,前端已經(jīng)非常廣泛的進(jìn)行使用了月幌。
1) Vector 語(yǔ)法簡(jiǎn)介
通過(guò)使用它的Path標(biāo)簽碍讯,幾乎可以實(shí)現(xiàn)SVG中的其它所有標(biāo)簽,雖然可能會(huì)復(fù)雜一點(diǎn)扯躺,
但這些東西都是可以通過(guò)工具來(lái)完成的捉兴,所以,不用擔(dān)心寫(xiě)起來(lái)會(huì)很復(fù)雜录语。
(1)Path指令解析如下所示:
M = moveto(M X,Y) :將畫(huà)筆移動(dòng)到指定的坐標(biāo)位置倍啥,相當(dāng)于 android Path 里的moveTo()
L = lineto(L X,Y) :畫(huà)直線到指定的坐標(biāo)位置,相當(dāng)于 android Path 里的lineTo()
H = horizontal lineto(H X):畫(huà)水平線到指定的X坐標(biāo)位置
V = vertical lineto(V Y):畫(huà)垂直線到指定的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)閉路徑(會(huì)自動(dòng)繪制鏈接起點(diǎn)和終點(diǎn))
注意蒲稳,’M’處理時(shí)氮趋,只是移動(dòng)了畫(huà)筆, 沒(méi)有畫(huà)任何東西江耀。
注意:1.關(guān)于這些語(yǔ)法剩胁,開(kāi)發(fā)者不需要全部精通,而是能夠看懂即可祥国,這些path標(biāo)簽及數(shù)據(jù)生成都可以交給工具來(lái)實(shí)現(xiàn)昵观。
(一般美工來(lái)幫你搞定!PS、Illustrator等等都支持導(dǎo)出SVG圖片)
2.程序員:沒(méi)必要去學(xué)習(xí)使用這些設(shè)計(jì)工具索昂,開(kāi)發(fā)者可以利用一些工具建车,自己轉(zhuǎn)換一些比較基礎(chǔ)的圖像,
如:http://inloop.github.io/svg2android/
3.還可以使用SVG的編輯器來(lái)進(jìn)行SVG圖像的編寫(xiě)椒惨,例如: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.reibang.com/p/d6c39f2dd5e7
AS會(huì)自動(dòng)生成兼容性圖片(高版本會(huì)生成xxx.xml的SVG圖片康谆;低版本會(huì)自動(dòng)生成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/
兼容問(wèn)題领斥,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前面添加一個(gè)flag設(shè)置
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
2.1 ImageView/ImageButton
XML app:srcCompat
代碼里面使用無(wú)區(qū)別
2.2 Button 不支持app:srcCompat
Xml 使用在Button的selector
2.3 RadioButton 直接使用
2.4 textview的drawable 直接使用
2.5 使用的動(dòng)態(tài)Vector Drawable
主要是不能直接修改 pathData
不能使用自定義interpolator
SVG使用
實(shí)現(xiàn)思路:
第一步 下載含有中國(guó)地圖的 SVG
第二步 用http://inloop.github.io/svg2android/ 網(wǎng)站 將svg資源轉(zhuǎn)換成相應(yīng)的 Android代碼
第三步 利用Xml解析SVG的代碼 封裝成javaBean 最重要的得到Path
第四步 重寫(xiě)OnDraw方法 利用Path繪制中國(guó)地圖
第五步 重寫(xiě)OnTouchEvent方法,記錄手指觸摸位置盛撑,判斷這個(gè)位置是否坐落在某個(gè)省份上碎节。代碼
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)備畫(huà)筆
mPaint = new Paint();
mPaint.setAntiAlias(true);
this.context = context;
thread.start();
//手勢(shì)處理類
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){
//繪制點(diǎn)擊后的背景
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);
}
}
//觸摸點(diǎn)是否在這個(gè)省的path內(nèi)
public boolean isTouch(int x, int y) {
//構(gòu)造一個(gè)矩形對(duì)象
RectF rectF=new RectF();
//返回路徑控制點(diǎn)的計(jì)算邊界保存到rectF
path.computeBounds(rectF,true);
//構(gòu)造一個(gè)區(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);
}