androidgraphics
㈠ android設置控制項樣式(邊框顏色,圓角)和圖片樣式(圓角)
本文鏈接:https://blog.csdn.net/weixin_37577039/article/details/79090433
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorAccent" />
<!-- 這里是設置為四周 也可以單獨設置某個位置為圓角-->
<corners android:topLeftRadius="5dp"
android:topRightRadius="5dp"
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"/>
<stroke android:width="1dp" android:color="#000000" />
</shape
```
```
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 邊框顏色值 -->
<item>
<shape>
<solid android:color="#3bbaff" />
</shape>
</item>
<!--這個是按鈕邊框設置為四周 並且寬度為1-->
<item
android:right="1dp"
android:left="1dp"
android:top="1dp"
android:bottom="1dp">
<shape>
<!--這個是背景顏色-->
<solid android:color="#ffffff" />
<!--這個是按鈕中的字體與按鈕內的四周邊距-->
<padding android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
</item>
</layer-list>
```
使用:
```android:background="@drawable/button_edge"```
```
<?xml version="1.0" encoding="UTF-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充的顏色 -->
<solid android:color="#FFFFFF" />
<!-- android:radius 弧形的半徑 -->
<!-- 設置按鈕的四個角為弧形 -->
<corners
android:radius="5dip" />
<!--也可單獨設置-->
<!-- <corners -->
<!-- android:topLeftRadius="10dp"-->
<!-- android:topRightRadius="10dp"-->
<!-- android:bottomRightRadius="10dp"-->
<!-- android:bottomLeftRadius="10dp"-->
<!-- /> -->
**設置文字padding**
<!-- padding:Button裡面的文字與Button邊界的間隔 -->
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp"
/>
</shape>
```
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"/>
</shape>
```
使用:
```
android:background="@drawable/image_circle"
```
```
Glide.with(MainActivity.this).load(croppedUri)
.transform(new GlideRectRound(MainActivity.this,6)).into(headIcon);
```
```
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.Log;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
/**
* Created by SiHao on 2018/3/3.
* Glide 的 圓角 圖片 工具類
*/
public class GlideRectRound extends BitmapTransformation {
private static float radius = 0f;
// 構造方法1 無傳入圓角度數 設置默認值為5
public GlideRectRound(Context context) {
this(context, 5);
}
// 構造方法2 傳入圓角度數
public GlideRectRound(Context context, int dp) {
super(context);
// 設置圓角度數
radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
// 重寫該方法 返回修改後的Bitmap
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return rectRoundCrop(pool,toTransform);
}
@Override
public String getId() {
Log.e("getID",getClass().getName() + Math.round(radius));
return getClass().getName() + Math.round(radius); // 四捨五入
}
private Bitmap rectRoundCrop(BitmapPool pool, Bitmap source){
if (source == null) return null;
Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // ARGB_4444——代表4x4位ARGB點陣圖,ARGB_8888——代表4x8位ARGB點陣圖
if (result == null) {
result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
// setShader 對圖像進行渲染
// 子類之一 BitmapShader設置Bitmap的變換 TileMode 有CLAMP (取bitmap邊緣的最後一個像素進行擴展),REPEAT(水平地重復整張bitmap)
//MIRROR(和REPEAT類似,但是每次重復的時候,將bitmap進行翻轉)
paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true); // 抗鋸齒
RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
}
```
圓角:
```
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
/**
* Created by SiHao on 2018/3/3.
* Glide圓形圖片工具類
*/
public class GlideCircleBitmap extends BitmapTransformation{
public GlideCircleBitmap(Context context) {
super(context);
}
// 重寫該方法 返回修改後的Bitmap
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
@Override
public String getId() {
return getClass().getName();
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
// 邊長取長寬最小值
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);// ARGB_4444——代表4x4位ARGB點陣圖,ARGB_8888——代表4x8位ARGB點陣圖
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
// setShader 對圖像進行渲染
// 子類之一 BitmapShader設置Bitmap的變換 TileMode 有CLAMP (取bitmap邊緣的最後一個像素進行擴展),REPEAT(水平地重復整張bitmap)
//MIRROR(和REPEAT類似,但是每次重復的時候,將bitmap進行翻轉)
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);// 抗鋸齒
// 半徑取 size的一半
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
}
```
```
URL url = new URL(String類型的字元串); //將String類型的字元串轉換為URL格式
holder.UserImage.setImageBitmap(BitmapFactory.decodeStream(url.openStream()));
```
```
//得到資源文件的BitMap
Bitmap image= BitmapFactory.decodeResource(getResources(),R.drawable.dog);
//創建RoundedBitmapDrawable對象
RoundedBitmapDrawable roundImg =RoundedBitmapDrawableFactory.create(getResources(),image);
//抗鋸齒
roundImg.setAntiAlias(true);
//設置圓角半徑
roundImg.setCornerRadius(30);
//設置顯示圖片
imageView.setImageDrawable(roundImg);
```
```
//如果是圓的時候,我們應該把bitmap圖片進行剪切成正方形, 然後再設置圓角半徑為正方形邊長的一半即可
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.dog);
Bitmap bitmap = null;
//將長方形圖片裁剪成正方形圖片
if (image.getWidth() == image.getHeight()) {
bitmap = Bitmap.createBitmap(image, image.getWidth() / 2 - image.getHeight() / 2, 0, image.getHeight(), image.getHeight());
} else {
bitmap = Bitmap.createBitmap(image, 0, image.getHeight() / 2 - image.getWidth() / 2, image.getWidth(), image.getWidth());
}
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
//圓角半徑為正方形邊長的一半
roundedBitmapDrawable.setCornerRadius(bitmap.getWidth() / 2);
//抗鋸齒
roundedBitmapDrawable.setAntiAlias(true);
imageView.setImageDrawable(roundedBitmapDrawable);
```
㈡ Android如何純java代碼實現字體陰影效果
Android實現純java代碼字體陰影效果,主要是通過activity的draw方法,進行重新繪制,如下代碼:
packagecanvas.test;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.content.Context;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Canvas;
importandroid.graphics.Color;
importandroid.graphics.Paint;
importandroid.graphics.PorterDuff;
importandroid.graphics.PorterDuff.Mode;
importandroid.graphics.PorterDuffXfermode;
importandroid.graphics.Rect;
importandroid.graphics.RectF;
importandroid.graphics.drawable.Drawable;
importandroid.view.View;
{
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(newImageEffect(this));
}
classImageEffectextendsView{
Paintpaint;
publicImageEffect(Contextcontext){
super(context);
paint=newPaint();//初始化畫筆,為後面陰影效果使用。
paint.setAntiAlias(true);//去除鋸齒。
paint.setShadowLayer(5f,5.0f,5.0f,Color.BLACK);//設置陰影層,這是關鍵。
paint.setXfermode(newPorterDuffXfermode(Mode.SRC_IN));
}
@Override
publicvoidonDraw(Canvascanvas){
super.onDraw(canvas);
intposX=20;
intposY=50;
intPicWidth,PicHegiht;
Drawabledrawable=getResources().getDrawable(R.drawable.button);
Drawabledbe=getResources().getDrawable(R.drawable.button).mutate();//如果不調用mutate方法,則原圖也會被改變,因為調用的資源是同一個,所有對象是共享狀態的。
DrawabledrawTest=getResources().getDrawable(R.drawable.button);
Bitmapbmp=BitmapFactory.decodeResource(getResources(),R.drawable.button);
PicWidth=drawable.getIntrinsicWidth();
PicHegiht=drawable.getIntrinsicHeight();
drawTest.setBounds(posX,(2*posY)+PicHegiht,posX+PicWidth,(2*posY)+2*PicHegiht);
drawable.setBounds(posX,posY,posX+PicWidth,posY+PicHegiht);
dbe.setBounds(0,0,PicWidth,PicHegiht);
canvas.drawColor(Color.WHITE);//設置畫布顏色
canvas.save(Canvas.MATRIX_SAVE_FLAG);
dbe.setColorFilter(0x7f000000,PorterDuff.Mode.SRC_IN);
canvas.translate(posX+(int)(0.9*PicWidth/2),posY+PicHegiht/2);//圖像平移為了剛好在原圖後形成影子效果。
canvas.skew(-0.9F,0.0F);//圖像傾斜效果。
canvas.scale(1.0f,0.5f);//圖像(其實是畫布)縮放,Y方向縮小為1/2。
dbe.draw(canvas);//此處為畫原圖像影子效果圖,比原圖先畫,則會在下層。
drawable.clearColorFilter();
canvas.restore();
canvas.save(Canvas.MATRIX_SAVE_FLAG);
drawable.draw(canvas);//此處為畫原圖像,由於canvas有層次效果,因此會蓋在影子之上。
canvas.restore();
//默認無效果原圖
canvas.save(Canvas.MATRIX_SAVE_FLAG);
drawTest.draw(canvas);
canvas.restore();
//圖片陰影效果
canvas.save(Canvas.MATRIX_SAVE_FLAG);
//Rectrect=newRect(2*posX+PicWidth,2*posY+PicHegiht,2*posX+2*PicWidth,2*posY+2*PicHegiht);//此為理論上的陰影圖坐標
Rectrect=newRect(2*posX+PicWidth+3,2*posY+PicHegiht+3,2*posX+2*PicWidth-2,2*posY+2*PicHegiht-2);
//由於圖片的實際尺寸比顯示出來的圖像要大一些,因此需要適當更改下大小,以達到較好的效果
RectFrectF=newRectF(rect);
canvas.drawRoundRect(rectF,10f,10f,paint);//在原有矩形基礎上,畫成圓角矩形,同時帶有陰影層。
canvas.drawBitmap(bmp,2*posX+PicWidth,2*posY+PicHegiht,null);//畫上原圖。
canvas.restore();
}
}
}
㈢ java.io.NotSerializableException: android.graphics.Paint
應該是沒有序列化。序列化可以將內存中的類寫入文件或資料庫中。比如user類。序列化代碼:public class UserInfo implements Serializable { }
tomcat停止時,session要將對象信息序列化到硬碟,tomcat重啟時,再反序列化到session中。這個異常還是我說的那個你沒有把你的類序列化。只要在你的類名後加上implements Serializable就行了。
㈣ 在Android中要實現圖表統計該怎麼做
package com.yzxy.draw;
import java.util.ArrayList;
import java.util.HashMap;
import com.yzxy.draw.tools.Tools;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
@SuppressLint("ViewConstructor")
class MyTuView extends View{
public static final int RECT_SIZE = 10;
private Point mSelectedPoint = null;
public static enum Mstyle
{
Line,scroll
}
private Mstyle mstyle=Mstyle.Line;
private Point[] mPoints = new Point[8];
Context context;
Activity act;
int bheight=0;
Tools tool=new Tools();
HashMap map;
ArrayList dlk;
int totalvalue=30;
int pjvalue=5;
String xstr,ystr;
int margint=15;
int marginb=40;
int c=0;
int resid=0;
Boolean isylineshow;
public MyTuView(Context context,HashMap map,int totalvalue,int pjvalue,String xstr,String ystr,Boolean isylineshow)
{
super(context);
this.context=context;
this.act = (Activity)context;
this.map=map;
this.totalvalue=totalvalue;
this.pjvalue=pjvalue;
this.xstr=xstr;
this.ystr=ystr;
this.isylineshow=isylineshow;
act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// canvas.drawColor(Color.GRAY);
if(c!=0)
this.setbg(c);
if(resid!=0)
this.setBackgroundResource(resid);
dlk=tool.getintfrommap(map);
int height=getHeight();
if(bheight==0)
bheight=height-marginb;
int width=getWidth();
Log.i("w", getWidth()+":"+getHeight());
int blwidh=tool.dip2px(context,50);
int pjsize=totalvalue/pjvalue;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.GRAY);
paint.setStrokeWidth(1);
paint.setStyle(Style.STROKE);
// 畫直線(橫向)
for(int i=0;i xlist=new ArrayList();//記錄每個x的值
//畫直線(縱向)
for(int i=0;i dlk,HashMap map,ArrayList xlist,int max,int h)
{
Point[] points=new Point[dlk.size()];
for(int i=0;i getMap() {
return map;
}
public void setMap(HashMap map) {
this.map = map;
}
public int getTotalvalue() {
return totalvalue;
}
public void setTotalvalue(int totalvalue) {
this.totalvalue = totalvalue;
}
public int getPjvalue() {
return pjvalue;
}
public void setPjvalue(int pjvalue) {
this.pjvalue = pjvalue;
}
public String getXstr() {
return xstr;
}
public void setXstr(String xstr) {
this.xstr = xstr;
}
public String getYstr() {
return ystr;
}
public void setYstr(String ystr) {
this.ystr = ystr;
}
public int getMargint() {
return margint;
}
public void setMargint(int margint) {
this.margint = margint;
}
public Boolean getIsylineshow() {
return isylineshow;
}
public void setIsylineshow(Boolean isylineshow) {
this.isylineshow = isylineshow;
}
public int getMarginb() {
return marginb;
}
public void setMarginb(int marginb) {
this.marginb = marginb;
}
public Mstyle getMstyle() {
return mstyle;
}
public void setMstyle(Mstyle mstyle) {
this.mstyle = mstyle;
}
public int getBheight() {
return bheight;
}
public void setBheight(int bheight) {
this.bheight = bheight;
}
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
public int getResid() {
return resid;
}
public void setResid(int resid) {
this.resid = resid;
}
}
代碼片段
package com.yzxy.draw.tools;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
public class Tools
{
private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/yueqiu/";
public int dip2px(Context context, float dpValue)
{
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public int px2dip(Context context, float pxValue)
{
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public ArrayList getintfrommap(HashMap map)
{
ArrayList dlk=new ArrayList();
int position=0;
@SuppressWarnings("rawtypes")
Set set= map.entrySet();
@SuppressWarnings("rawtypes")
Iterator iterator = set.iterator();
while(iterator.hasNext())
{
@SuppressWarnings("rawtypes")
Map.Entry mapentry = (Map.Entry)iterator.next();
dlk.add((Double)mapentry.getKey());
}
for(int i=0;i
代碼片段
package com.yzxy.draw;
import java.io.IOException;
import java.util.HashMap;
import com.yzxy.draw.MyTuView.Mstyle;
import com.yzxy.draw.tools.Tools;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.Color;
public class MainActivity extends Activity {
MyTuView tu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HashMap map=new HashMap();
map.put(1.0, 8.0);
map.put(7.0, 130.0);
map.put(2.0, 4.0);
map.put(3.0, 1.0);
map.put(4.0, 18.0);
map.put(5.0, 160.0);
map.put(6.0, 180.0);
map.put(8.1, 133.5);
tu=new MyTuView(this,map,200,50,"x","y",false);
// tu.setC(Color.CYAN);
tu.setResid(R.drawable.bg);
// tu.setBheight(200);
tu.setTotalvalue(200);
tu.setPjvalue(50);
tu.setXstr("x");
tu.setYstr("y");
tu.setMargint(20);
tu.setBackgroundColor(Color.WHITE);
tu.setMarginb(50);
tu.setMstyle(Mstyle.scroll);
RelativeLayout rela=getlayout(R.layout.activity_main);
rela.addView(tu);
LayoutParams parm=new LayoutParams(1200,400);
parm.setMargins(50, 50, 50, 100);
tu.setLayoutParams(parm);
setContentView(rela);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// TODO Auto-generated method stub
if(item.getItemId() == R.id.menu_settings)
{
if (false == tu.isDrawingCacheEnabled())
{
tu.setDrawingCacheEnabled(true);
}
Bitmap bitmap = tu.getDrawingCache();
Tools tool=new Tools();
try {
Boolean b=tool.saveFile(bitmap, "aaaa.png");
if(b)
Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(item.getItemId() == R.id.menu_ch)
{
HashMap map=new HashMap();
map.put(1.0, 21.0);
map.put(3.0, 25.0);
map.put(4.0, 32.0);
map.put(5.0, 31.0);
map.put(6.0, 26.0);
tu.setTotalvalue(40);
tu.setPjvalue(10);
tu.setMap(map);
tu.setIsylineshow(true);
tu.postInvalidate();
}
if(item.getItemId() == R.id.menu_ch2)
{
HashMap map=new HashMap();
map.put(1.0, 41.0);
map.put(3.0, 25.0);
map.put(4.0, 32.0);
map.put(5.0, 41.0);
map.put(6.0, 16.0);
map.put(7.0, 36.0);
map.put(8.0, 26.0);
tu.setTotalvalue(50);
tu.setPjvalue(10);
tu.setMap(map);
tu.setMstyle(Mstyle.Line);
tu.setIsylineshow(false);
tu.postInvalidate();
}
return true;
}
public RelativeLayout getlayout(int r)
{
LayoutInflater inflater = (LayoutInflater)getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE );
try {
XmlResourceParser parser = getResources().getLayout(r);
RelativeLayout layout = (RelativeLayout) inflater.inflate(parser, null);
return layout;
}catch (Exception e) {
// TODO: handle exception
}
return null;
}
}
㈤ android 怎麼畫2層圓環
Android繪制兩層圓環,可以使用自定義View,繼承View,重寫裡面的Ondraw方法,花兩個同心圓,示例如下:
packagecom.cn.myvn;
importandroid.content.Context;
importandroid.graphics.Canvas;
importandroid.graphics.Paint;
importandroid.util.AttributeSet;
importandroid.view.View;
{
privatefinalPaintpaint;
privatefinalContextcontext;
publicRingView(Contextcontext){
//TODOAuto-generatedconstructorstub
this(context,null);
}
publicRingView(Contextcontext,AttributeSetattrs){
super(context,attrs);
//TODOAuto-generatedconstructorstub
this.context=context;
this.paint=newPaint();
this.paint.setAntiAlias(true);//消除鋸齒
this.paint.setStyle(Paint.Style.STROKE);//繪制空心圓
}
@Override
protectedvoidonDraw(Canvascanvas){
//TODOAuto-generatedmethodstub
intcenter=getWidth()/2;
intinnerCircle=dip2px(context,83);//設置內圓半徑
intringWidth=dip2px(context,5);//設置圓環寬度
//繪制內圓
this.paint.setARGB(155,167,190,206);
this.paint.setStrokeWidth(2);
canvas.drawCircle(center,center,innerCircle,this.paint);
//繪制圓環
this.paint.setARGB(255,212,225,233);
this.paint.setStrokeWidth(ringWidth);
canvas.drawCircle(center,center,innerCircle+1+ringWidth/2,this.paint);
//繪制外圓
this.paint.setARGB(155,167,190,206);
this.paint.setStrokeWidth(2);
canvas.drawCircle(center,center,innerCircle+ringWidth,this.paint);
super.onDraw(canvas);
}
}
㈥ android怎麼用paint實現圖像的漸變出現
在android.graphics中提供了有關Gradient字樣的類,例如LinearGradient線性漸變、 RadialGradient徑向漸變和SweepGradient角度漸變三種,他們的基類為android.graphics.Shader。為了演 示圖像漸變效果,下面給出一個簡單的實例。
一、LinearGradient線性漸變
在android平台中提供了兩種重載方式來實例化該類分別為,他們的不同之處為參數中第一種方法可以用顏色數組,和位置來實現更細膩的過渡效果, 比如顏 色采樣int[] colors數組中存放20種顏色,則漸變將會逐一處理。而第二種方法參數僅為起初顏色color0和最終顏色color1。
LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile)
LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, Shader.TileMode tile)
使用實例如下:
Paint p=new Paint();
LinearGradient lg=new LinearGradient(0,0,100,100,Color.RED,Color.BLUE,Shader.TileMode.MIRROR); //參數一為漸變起初點坐標x位置,參數二為y軸位置,參數三和四分辨對應漸變終點,最後參數為平鋪方式,這里設置為鏡像
剛才已經講到Gradient是基於Shader類,所以我們通過Paint的setShader方法來設置這個漸變,代碼如下:
p.setShader(lg);
canvas.drawCicle(0,0,200,p); //參數3為畫圓的半徑,類型為float型。
二、RadialGradient鏡像漸變
有了上面的基礎,我們一起來了解下徑向漸變。和上面參數唯一不同的是,徑向漸變第三個參數是半徑,其他的和線性漸變相同。
RadialGradient(float x, float y, float radius, int[] colors, float[] positions, Shader.TileMode tile)
RadialGradient(float x, float y, float radius, int color0, int color1, Shader.TileMode tile)
三、SweepGradient角度漸變
對於一些3D立體效果的漸變可以嘗試用角度漸變來完成一個圓錐形,相對來說比上面更簡單,前兩個參數為中心點,然後通過載入的顏色來平均的漸變渲染。
SweepGradient(float cx, float cy, int[] colors, float[] positions) //對於最後一個參數SDK上的描述為May be NULL. The relative position of each corresponding color in the colors array, beginning with 0 and ending with 1.0. If the values are not monotonic, the drawing may proce unexpected results. If positions is NULL, then the colors are automatically spaced evenly.,所以建議使用下面的重載方法,本方法一般為NULL即可。
SweepGradient(float cx, float cy, int color0, int color1)
到此,希望大家對圖像特效處理有了一定的認識,了解這些對打好Android游戲開發的基礎很有好處。
轉載